db5da1e4a6aa6a172e2db52f777877ab4217cfd9
[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.appclcm.LcmRequest;
34 import org.onap.policy.appclcm.LcmRequestWrapper;
35 import org.onap.policy.appclcm.LcmResponse;
36 import org.onap.policy.appclcm.LcmResponseWrapper;
37 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
38 import org.onap.policy.common.endpoints.event.comm.TopicListener;
39 import org.onap.policy.common.endpoints.event.comm.TopicSink;
40 import org.onap.policy.controlloop.ControlLoopEventStatus;
41 import org.onap.policy.controlloop.ControlLoopNotificationType;
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 ControlLoopFailureTest extends ControlLoopBase implements TopicListener {
47
48     private UUID requestId2;
49     private UUID requestId3;
50     private int eventCount;
51     private int nsuccess = 0;
52     private int nreject = 0;
53
54     /**
55      * Setup simulator.
56      */
57     @BeforeClass
58     public static void setUpBeforeClass() {
59         ControlLoopBase.setUpBeforeClass(
60             "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
61                             + "/src/main/resources/__closedLoopControlName__.drl",
62             "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
63             "service=ServiceDemo;resource=Res1Demo;type=operational",
64             "CL_vCPE",
65             "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
66     }
67
68     /**
69      * This test case tests the scenario where 3 events occur and 2 of the requests refer to the
70      * same target entity while the 3rd is for another entity. The expected result is that the event
71      * with the duplicate target entity will have a final success result for one of the events, and
72      * a rejected message for the one that was unable to obtain the lock. The event that is
73      * referring to a different target entity should be able to obtain a lock since it is a
74      * different target. After processing of all events there should only be the params object left
75      * in memory.
76      */
77     @Test
78     public void targetLockedTest() {
79
80         /*
81          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
82          * to be pulled from the queue
83          */
84         for (TopicSink sink : noopTopics) {
85             assertTrue(sink.start());
86             sink.register(this);
87         }
88
89         /*
90          * Create a unique requestId
91          */
92         requestId = UUID.randomUUID();
93
94         /*
95          * This will be a unique request for another target entity
96          */
97         requestId2 = UUID.randomUUID();
98
99         /*
100          * This will be a request duplicating the target entity of the first request
101          */
102         requestId3 = UUID.randomUUID();
103
104         /*
105          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
106          * through the rules
107          */
108         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vnf01");
109
110         /*
111          * Send a second event for a different target to ensure there are no problems with obtaining
112          * a lock
113          */
114         sendEvent(pair.first, requestId2, ControlLoopEventStatus.ONSET, "vnf02");
115
116         /*
117          * Send a third event requesting an action for a duplicate target entity
118          */
119         sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
120
121         kieSession.fireUntilHalt();
122
123         // allow object clean-up
124         kieSession.fireAllRules();
125
126         // should be one success and one failure for vnf01
127         assertEquals(1, nsuccess);
128         assertEquals(1, nreject);
129
130         /*
131          * The only fact in memory should be Params
132          */
133         assertEquals(1, kieSession.getFactCount());
134
135         /*
136          * Print what's left in memory
137          */
138         dumpFacts(kieSession);
139     }
140
141     /*
142      * (non-Javadoc)
143      *
144      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
145      */
146     @Override
147     public synchronized void onTopicEvent(CommInfrastructure commType, String topic, String event) {
148         /*
149          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
150          * of type active
151          */
152         Object obj = null;
153         if ("POLICY-CL-MGT".equals(topic)) {
154             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
155                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
156         } else if ("APPC-LCM-READ".equals(topic)) {
157             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
158                     org.onap.policy.appclcm.LcmRequestWrapper.class);
159         }
160         assertNotNull(obj);
161         if (obj instanceof VirtualControlLoopNotification) {
162             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
163             String policyName = notification.getPolicyName();
164             if (policyName.endsWith("EVENT")) {
165                 logger.debug("Rule Fired: " + notification.getPolicyName());
166                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
167             } else if (policyName.endsWith("DENIED")) {
168                 logger.debug("Rule Fired: " + notification.getPolicyName());
169                 assertTrue(ControlLoopNotificationType.REJECTED.equals(notification.getNotification()));
170                 assertNotNull(notification.getMessage());
171                 assertTrue(notification.getMessage().contains("is already locked"));
172                 if (requestId.equals(notification.getRequestId()) || requestId3.equals(notification.getRequestId())) {
173                     ++nreject;
174                 }
175                 if (++eventCount == 3) {
176                     kieSession.halt();
177                 }
178             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
179                 logger.debug("Rule Fired: " + notification.getPolicyName());
180                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
181                 assertNotNull(notification.getMessage());
182                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
183             } else if (policyName.endsWith("GUARD.RESPONSE")) {
184                 logger.debug("Rule Fired: " + notification.getPolicyName());
185                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
186                 assertNotNull(notification.getMessage());
187                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
188             } else if (policyName.endsWith("GUARD_PERMITTED")) {
189                 logger.debug("Rule Fired: " + notification.getPolicyName());
190                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
191                 assertNotNull(notification.getMessage());
192                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
193             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
194                 logger.debug("Rule Fired: " + notification.getPolicyName());
195                 kieSession.halt();
196                 logger.debug("The operation timed out");
197                 fail("Operation Timed Out");
198             } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
199                 logger.debug("Rule Fired: " + notification.getPolicyName());
200                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
201                 assertNotNull(notification.getMessage());
202                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
203                 if (requestId.equals(notification.getRequestId()) || requestId3.equals(notification.getRequestId())) {
204                     sendEvent(pair.first, notification.getRequestId(), ControlLoopEventStatus.ABATED, "vnf01");
205                 } else if (requestId2.equals(notification.getRequestId())) {
206                     sendEvent(pair.first, requestId2, ControlLoopEventStatus.ABATED, "vnf02");
207                 }
208             } else if (policyName.endsWith("EVENT.MANAGER")) {
209                 logger.debug("Rule Fired: " + notification.getPolicyName());
210                 if (requestId.equals(notification.getRequestId()) || requestId3.equals(notification.getRequestId())) {
211                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
212                     ++nsuccess;
213                 } else {
214                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
215                 }
216                 if (++eventCount == 3) {
217                     kieSession.halt();
218                 }
219             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
220                 logger.debug("Rule Fired: " + notification.getPolicyName());
221                 kieSession.halt();
222                 logger.debug("The control loop timed out");
223                 fail("Control Loop Timed Out");
224             }
225         } else if (obj instanceof LcmRequestWrapper) {
226             /*
227              * The request should be of type LCMRequestWrapper and the subrequestid should be 1
228              */
229             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
230             LcmRequest appcRequest = dmaapRequest.getBody();
231             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
232
233             logger.debug("\n============ APPC received the request!!! ===========\n");
234
235             /*
236              * Simulate a success response from APPC and insert the response into the working memory
237              */
238             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
239             LcmResponse appcResponse = new LcmResponse(appcRequest);
240             appcResponse.getStatus().setCode(400);
241             appcResponse.getStatus().setMessage("AppC success");
242             dmaapResponse.setBody(appcResponse);
243
244             /*
245              * Interrupting with a different request for the same target entity to check if lock
246              * will be denied
247              */
248             if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) {
249                 sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
250             }
251             kieSession.insert(dmaapResponse);
252         }
253     }
254
255     /**
256      * This method is used to simulate event messages from DCAE that start the control loop (onset
257      * message) or end the control loop (abatement message).
258      *
259      * @param policy the controlLoopName comes from the policy
260      * @param requestId the requestId for this event
261      * @param status could be onset or abated
262      * @param target the target entity to take an action on
263      */
264     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String target) {
265         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
266         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
267         event.setRequestId(requestId);
268         event.setTarget("generic-vnf.vnf-id");
269         event.setClosedLoopAlarmStart(Instant.now());
270         event.setAai(new HashMap<>());
271         event.getAai().put("generic-vnf.vnf-id", target);
272         event.getAai().put("vserver.vserver-name", "OzVServer");
273         event.setClosedLoopEventStatus(status);
274         kieSession.insert(event);
275     }
276 }