move actors code in drools-applications to policy/models
[policy/models.git] / models-interactions / model-actors / actor.appclcm / src / test / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmActorServiceProviderTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * AppcServiceProviderTest
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.appclcm;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.fail;
28
29 import java.time.Instant;
30 import java.util.AbstractMap;
31 import java.util.HashMap;
32 import java.util.UUID;
33
34 import org.junit.AfterClass;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.onap.policy.aai.util.AaiException;
38 import org.onap.policy.appclcm.LcmCommonHeader;
39 import org.onap.policy.appclcm.LcmRequest;
40 import org.onap.policy.appclcm.LcmRequestWrapper;
41 import org.onap.policy.appclcm.LcmResponse;
42 import org.onap.policy.appclcm.LcmResponseWrapper;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
44 import org.onap.policy.controlloop.ControlLoopEventStatus;
45 import org.onap.policy.controlloop.ControlLoopOperation;
46 import org.onap.policy.controlloop.ControlLoopTargetType;
47 import org.onap.policy.controlloop.VirtualControlLoopEvent;
48 import org.onap.policy.controlloop.policy.Policy;
49 import org.onap.policy.controlloop.policy.PolicyResult;
50 import org.onap.policy.controlloop.policy.Target;
51 import org.onap.policy.controlloop.policy.TargetType;
52 import org.onap.policy.drools.system.PolicyEngine;
53 import org.onap.policy.simulators.Util;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57
58 public class AppcLcmActorServiceProviderTest {
59
60     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProviderTest.class);
61
62     private static final VirtualControlLoopEvent onsetEvent;
63     private static final ControlLoopOperation operation;
64     private static final Policy policy;
65     private static final LcmResponseWrapper dmaapResponse;
66
67     private static final String RECIPE_RESTART = "Restart";
68     private static final String RECIPE_REBUILD = "Rebuild";
69     private static final String RECIPE_MIGRATE = "Migrate";
70
71     static {
72         /*
73          * Construct an onset with an AAI subtag containing generic-vnf.vnf-id and a target type of
74          * VM.
75          */
76         onsetEvent = new VirtualControlLoopEvent();
77         onsetEvent.setClosedLoopControlName("closedLoopControlName-Test");
78         onsetEvent.setRequestId(UUID.randomUUID());
79         onsetEvent.setClosedLoopEventClient("tca.instance00001");
80         onsetEvent.setTargetType(ControlLoopTargetType.VM);
81         onsetEvent.setTarget("generic-vnf.vnf-name");
82         onsetEvent.setFrom("DCAE");
83         onsetEvent.setClosedLoopAlarmStart(Instant.now());
84         onsetEvent.setAai(new HashMap<>());
85         onsetEvent.getAai().put("generic-vnf.vnf-name", "fw0001vm001fw001");
86         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
87
88         /* Construct an operation with an APPC actor and restart operation. */
89         operation = new ControlLoopOperation();
90         operation.setActor("APPC");
91         operation.setOperation("Restart");
92         operation.setTarget("VM");
93         operation.setEnd(Instant.now());
94         operation.setSubRequestId("1");
95
96         /* Construct a policy specifying to restart vm. */
97         policy = new Policy();
98         policy.setName("Restart the VM");
99         policy.setDescription("Upon getting the trigger event, restart the VM");
100         policy.setActor("APPC");
101         policy.setTarget(new Target(TargetType.VNF));
102         policy.setRecipe("Restart");
103         policy.setPayload(null);
104         policy.setRetry(2);
105         policy.setTimeout(300);
106
107         /* A sample DMAAP request wrapper. */
108         LcmRequestWrapper dmaapRequest = new LcmRequestWrapper();
109         dmaapRequest.setCorrelationId(onsetEvent.getRequestId().toString() + "-" + "1");
110         dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
111         dmaapRequest.setType("request");
112
113         /* A sample DMAAP response wrapper */
114         dmaapResponse = new LcmResponseWrapper();
115         dmaapResponse.setCorrelationId(onsetEvent.getRequestId().toString() + "-" + "1");
116         dmaapResponse.setRpcName(policy.getRecipe().toLowerCase());
117         dmaapResponse.setType("response");
118
119         /* Set environment properties */
120         PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
121         PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
122         PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
123
124         /* A sample APPC LCM request. */
125         LcmRequest appcRequest = new LcmRequest();
126
127         /* The following code constructs a sample APPC LCM Request */
128         appcRequest.setAction("restart");
129
130         HashMap<String, String> actionIdentifiers = new HashMap<>();
131         actionIdentifiers.put("vnf-id", "trial-vnf-003");
132
133         appcRequest.setActionIdentifiers(actionIdentifiers);
134
135         LcmCommonHeader commonHeader = new LcmCommonHeader();
136         commonHeader.setRequestId(onsetEvent.getRequestId());
137         commonHeader.setSubRequestId("1");
138         commonHeader.setOriginatorId(onsetEvent.getRequestId().toString());
139
140         appcRequest.setCommonHeader(commonHeader);
141
142         appcRequest.setPayload(null);
143
144         dmaapRequest.setBody(appcRequest);
145
146         /* The following code constructs a sample APPC LCM Response */
147         LcmResponse appcResponse = new LcmResponse(appcRequest);
148         appcResponse.getStatus().setCode(400);
149         appcResponse.getStatus().setMessage("Restart Successful");
150
151         dmaapResponse.setBody(appcResponse);
152     }
153
154     /**
155      * Set up before test class.
156      */
157     @BeforeClass
158     public static void setUpSimulator() {
159         try {
160             Util.buildAaiSim();
161         } catch (Exception e) {
162             fail(e.getMessage());
163         }
164     }
165
166     /**
167      * Tear down after test class.
168      */
169     @AfterClass
170     public static void tearDownSimulator() {
171         HttpServletServer.factory.destroy();
172     }
173
174     /**
175      * A test to construct an APPC LCM restart request.
176      */
177     @Test
178     public void constructRestartRequestTest() {
179
180         LcmRequestWrapper dmaapRequest =
181                 AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, policy, "vnf01");
182
183         /* The service provider must return a non null DMAAP request wrapper */
184         assertNotNull(dmaapRequest);
185
186         /* The DMAAP wrapper's type field must be request */
187         assertEquals("request", dmaapRequest.getType());
188
189         /* The DMAAP wrapper's body field cannot be null */
190         assertNotNull(dmaapRequest.getBody());
191
192         LcmRequest appcRequest = dmaapRequest.getBody();
193
194         /* A common header is required and cannot be null */
195         assertNotNull(appcRequest.getCommonHeader());
196         assertEquals(appcRequest.getCommonHeader().getRequestId(), onsetEvent.getRequestId());
197
198         /* An action is required and cannot be null */
199         assertNotNull(appcRequest.getAction());
200         assertEquals("Restart", appcRequest.getAction());
201
202         /* Action Identifiers are required and cannot be null */
203         assertNotNull(appcRequest.getActionIdentifiers());
204         assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
205         assertEquals("vnf01", appcRequest.getActionIdentifiers().get("vnf-id"));
206
207         logger.debug("APPC Request: \n" + appcRequest.toString());
208     }
209
210     /**
211      * A test to process a successful APPC restart response.
212      */
213     @Test
214     public void processRestartResponseSuccessTest() {
215         AbstractMap.SimpleEntry<PolicyResult, String> result =
216                 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
217         assertEquals(PolicyResult.SUCCESS, result.getKey());
218         assertEquals("Restart Successful", result.getValue());
219     }
220
221     /**
222      * A test to map APPC response results to corresponding Policy results.
223      */
224     @Test
225     public void appcToPolicyResultTest() {
226
227         AbstractMap.SimpleEntry<PolicyResult, String> result;
228
229         /* If APPC accepts, PolicyResult is null */
230         dmaapResponse.getBody().getStatus().setCode(100);
231         dmaapResponse.getBody().getStatus().setMessage("ACCEPTED");
232         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
233         assertNull(result.getKey());
234
235         /* If APPC is successful, PolicyResult is success */
236         dmaapResponse.getBody().getStatus().setCode(400);
237         dmaapResponse.getBody().getStatus().setMessage("SUCCESS");
238         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
239         assertEquals(PolicyResult.SUCCESS, result.getKey());
240
241         /* If APPC returns an error, PolicyResult is failure exception */
242         dmaapResponse.getBody().getStatus().setCode(200);
243         dmaapResponse.getBody().getStatus().setMessage("ERROR");
244         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
245         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
246
247         /* If APPC rejects, PolicyResult is failure exception */
248         dmaapResponse.getBody().getStatus().setCode(300);
249         dmaapResponse.getBody().getStatus().setMessage("REJECT");
250         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
251         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
252
253         /* Test multiple reject codes */
254         dmaapResponse.getBody().getStatus().setCode(306);
255         dmaapResponse.getBody().getStatus().setMessage("REJECT");
256         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
257         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
258
259         dmaapResponse.getBody().getStatus().setCode(313);
260         dmaapResponse.getBody().getStatus().setMessage("REJECT");
261         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
262         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
263
264         /* If APPC returns failure, PolicyResult is failure */
265         dmaapResponse.getBody().getStatus().setCode(401);
266         dmaapResponse.getBody().getStatus().setMessage("FAILURE");
267         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
268         assertEquals(PolicyResult.FAILURE, result.getKey());
269
270         /* Test multiple failure codes */
271         dmaapResponse.getBody().getStatus().setCode(406);
272         dmaapResponse.getBody().getStatus().setMessage("FAILURE");
273         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
274         assertEquals(PolicyResult.FAILURE, result.getKey());
275
276         dmaapResponse.getBody().getStatus().setCode(450);
277         dmaapResponse.getBody().getStatus().setMessage("FAILURE");
278         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
279         assertEquals(PolicyResult.FAILURE, result.getKey());
280
281         /* If APPC returns partial success, PolicyResult is failure exception */
282         dmaapResponse.getBody().getStatus().setCode(500);
283         dmaapResponse.getBody().getStatus().setMessage("PARTIAL SUCCESS");
284         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
285         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
286
287         /* If APPC returns partial failure, PolicyResult is failure exception */
288         dmaapResponse.getBody().getStatus().setCode(501);
289         dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE");
290         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
291         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
292
293         /* Test multiple partial failure codes */
294         dmaapResponse.getBody().getStatus().setCode(599);
295         dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE");
296         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
297         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
298
299         dmaapResponse.getBody().getStatus().setCode(550);
300         dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE");
301         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
302         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
303
304         /* If APPC code is unknown to Policy, PolicyResult is failure exception */
305         dmaapResponse.getBody().getStatus().setCode(700);
306         dmaapResponse.getBody().getStatus().setMessage("UNKNOWN");
307         result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
308         assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
309     }
310
311     /**
312      * This test ensures that that if the the source entity is also the target entity, the source
313      * will be used for the APPC request.
314      */
315     @Test
316     public void sourceIsTargetTest() {
317         String resourceId = "82194af1-3c2c-485a-8f44-420e22a9eaa4";
318         String targetVnfId = null;
319         try {
320             targetVnfId = AppcLcmActorServiceProvider.vnfNamedQuery(resourceId, "vnf01");
321         } catch (AaiException e) {
322             logger.warn(e.toString());
323             fail("no vnf-id found");
324         }
325         assertNotNull(targetVnfId);
326         assertEquals("vnf01", targetVnfId);
327     }
328
329     /**
330      * THis test exercises getters not exercised in other tests.
331      */
332     @Test
333     public void testMethods() {
334         AppcLcmActorServiceProvider sp = new AppcLcmActorServiceProvider();
335
336         assertEquals("APPC", sp.actor());
337         assertEquals(4, sp.recipes().size());
338         assertEquals("VM", sp.recipeTargets("Restart").get(0));
339         assertEquals("vm-id", sp.recipePayloads("Restart").get(0));
340     }
341
342     @Test
343     public void payloadNotPassedWhenNotSupportedByRecipe() {
344         //given
345         Policy migratePolicy = constructPolicyWithRecipe(RECIPE_MIGRATE);
346         Policy rebuildPolicy = constructPolicyWithRecipe(RECIPE_REBUILD);
347         Policy restartPolicy = constructPolicyWithRecipe(RECIPE_RESTART);
348
349         // when
350         LcmRequestWrapper migrateRequest =
351             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, migratePolicy, "vnf01");
352         LcmRequestWrapper rebuildRequest =
353             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, rebuildPolicy, "vnf01");
354         LcmRequestWrapper restartRequest =
355             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, restartPolicy, "vnf01");
356
357         // then
358         assertNull(migrateRequest.getBody().getPayload());
359         assertNull(rebuildRequest.getBody().getPayload());
360         assertNull(restartRequest.getBody().getPayload());
361     }
362
363     @Test
364     public void payloadNotPassedWhenNotSuppliedOrEmpty() {
365         //given
366         Policy noPayloadPolicy = constructHealthCheckPolicyWithPayload(null);
367         Policy emptyPayloadPolicy = constructHealthCheckPolicyWithPayload(new HashMap<>());
368
369         // when
370         LcmRequestWrapper noPayloadRequest =
371             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, noPayloadPolicy, "vnf01");
372         LcmRequestWrapper emptyPayloadRequest =
373             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, emptyPayloadPolicy, "vnf01");
374
375
376         // then
377         assertNull(noPayloadRequest.getBody().getPayload());
378         assertNull(emptyPayloadRequest.getBody().getPayload());
379     }
380
381     @Test
382     public void payloadParsedProperlyForSinglePayloadParameter() {
383         // given
384         HashMap<String, String> payload = new HashMap<>();
385         payload.put("requestParameters", "{\"host-ip-address\":\"10.183.37.25\"}");
386         Policy otherPolicy = constructHealthCheckPolicyWithPayload(payload);
387
388         // when
389         LcmRequestWrapper dmaapRequest =
390             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, otherPolicy, "vnf01");
391
392         // then
393         assertEquals(dmaapRequest.getBody().getPayload(),
394             "{\"requestParameters\": {\"host-ip-address\":\"10.183.37.25\"}}");
395     }
396
397
398     @Test
399     public void payloadParsedProperlyForMultiplePayloadParameters() {
400         // given
401         HashMap<String, String> payload = new HashMap<>();
402         payload.put("requestParameters", "{\"host-ip-address\":\"10.183.37.25\"}");
403         payload.put("configurationParameters", "[{\"ip-addr\":\"$.vf-module-topology.vf-module-parameters.param[9]\","
404             + "\"oam-ip-addr\":\"$.vf-module-topology.vf-module-parameters.param[16]\","
405             + "\"enabled\":\"$.vf-module-topology.vf-module-parameters.param[23]\"}]");
406         Policy otherPolicy = constructHealthCheckPolicyWithPayload(payload);
407
408         // when
409         LcmRequestWrapper dmaapRequest =
410             AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, otherPolicy, "vnf01");
411
412         // then
413         assertEquals(dmaapRequest.getBody().getPayload(),
414             "{\"requestParameters\": "
415                 + "{\"host-ip-address\":\"10.183.37.25\"},"
416                 + "\"configurationParameters\": "
417                 + "[{\"ip-addr\":\"$.vf-module-topology.vf-module-parameters.param[9]\","
418                 + "\"oam-ip-addr\":\"$.vf-module-topology.vf-module-parameters.param[16]\","
419                 + "\"enabled\":\"$.vf-module-topology.vf-module-parameters.param[23]\"}]"
420                 + "}");
421     }
422
423     private Policy constructHealthCheckPolicyWithPayload(HashMap<String, String> payload) {
424         return constructHealthCheckPolicyWithPayloadAndRecipe(payload, "Health-Check");
425     }
426
427     private Policy constructPolicyWithRecipe(String recipe) {
428         return constructHealthCheckPolicyWithPayloadAndRecipe(null, recipe);
429     }
430
431     private Policy constructHealthCheckPolicyWithPayloadAndRecipe(HashMap<String, String> payload, String recipe) {
432         Policy otherPolicy = new Policy();
433         otherPolicy.setName("Perform health check");
434         otherPolicy.setDescription("Upon getting the trigger event, perform health check");
435         otherPolicy.setActor("APPC");
436         otherPolicy.setTarget(new Target(TargetType.VNF));
437         otherPolicy.setRecipe(recipe);
438         otherPolicy.setPayload(payload);
439         otherPolicy.setRetry(2);
440         otherPolicy.setTimeout(300);
441         return otherPolicy;
442     }
443 }