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