Make targetEntity a property
[policy/models.git] / models-interactions / model-actors / actor.cds / src / test / java / org / onap / policy / controlloop / actor / cds / GrpcOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020 Bell Canada. All rights reserved.
4  * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  */
19
20 package org.onap.policy.controlloop.actor.cds;
21
22 import static org.assertj.core.api.Assertions.assertThat;
23 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
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.assertSame;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.ArgumentMatchers.eq;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.verify;
33 import static org.mockito.Mockito.when;
34
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.UUID;
40 import java.util.concurrent.CompletableFuture;
41 import java.util.concurrent.CountDownLatch;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.Executor;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.TimeoutException;
46 import java.util.concurrent.atomic.AtomicBoolean;
47 import org.junit.AfterClass;
48 import org.junit.Before;
49 import org.junit.BeforeClass;
50 import org.junit.Test;
51 import org.mockito.Mock;
52 import org.mockito.MockitoAnnotations;
53 import org.onap.aai.domain.yang.GenericVnf;
54 import org.onap.aai.domain.yang.Pnf;
55 import org.onap.aai.domain.yang.ServiceInstance;
56 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
57 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
58 import org.onap.policy.aai.AaiCqResponse;
59 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
60 import org.onap.policy.cds.properties.CdsServerProperties;
61 import org.onap.policy.common.utils.coder.Coder;
62 import org.onap.policy.common.utils.coder.CoderException;
63 import org.onap.policy.common.utils.coder.StandardCoder;
64 import org.onap.policy.common.utils.coder.StandardCoderObject;
65 import org.onap.policy.common.utils.time.PseudoExecutor;
66 import org.onap.policy.controlloop.VirtualControlLoopEvent;
67 import org.onap.policy.controlloop.actor.aai.AaiGetPnfOperation;
68 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
69 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
70 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
71 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
72 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
73 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
74 import org.onap.policy.controlloop.policy.PolicyResult;
75 import org.onap.policy.controlloop.policy.Target;
76 import org.onap.policy.controlloop.policy.TargetType;
77 import org.onap.policy.simulators.CdsSimulator;
78 import org.onap.policy.simulators.Util;
79
80 public class GrpcOperationTest {
81     private static final String TARGET_ENTITY = "entity";
82     private static final String MY_VNF = "my-vnf";
83     private static final String MY_SVC_ID = "my-service-instance-id";
84     private static final String RESOURCE_ID = "my-resource-id";
85     private static final String CDS_BLUEPRINT_NAME = "vfw-cds";
86     private static final String CDS_BLUEPRINT_VERSION = "1.0.0";
87     private static final UUID REQUEST_ID = UUID.randomUUID();
88     private static final Coder coder = new StandardCoder();
89
90     protected static final Executor blockingExecutor = command -> {
91         Thread thread = new Thread(command);
92         thread.setDaemon(true);
93         thread.start();
94     };
95
96     private static CdsSimulator sim;
97
98     @Mock
99     private CdsProcessorGrpcClient cdsClient;
100     @Mock
101     private ControlLoopEventContext context;
102     private CdsServerProperties cdsProps;
103     private VirtualControlLoopEvent onset;
104     private PseudoExecutor executor;
105     private Target target;
106     private ControlLoopOperationParams params;
107     private GrpcConfig config;
108     private CompletableFuture<OperationOutcome> cqFuture;
109     private GrpcOperation operation;
110
111     @BeforeClass
112     public static void setUpBeforeClass() throws Exception {
113         sim = Util.buildCdsSim();
114     }
115
116     @AfterClass
117     public static void tearDownAfterClass() {
118         sim.stop();
119     }
120
121     /**
122      * Sets up the fields.
123      */
124     @Before
125     public void setUp() throws Exception {
126         MockitoAnnotations.initMocks(this);
127
128         // Setup the CDS properties
129         cdsProps = new CdsServerProperties();
130         cdsProps.setHost("10.10.10.10");
131         cdsProps.setPort(2000);
132         cdsProps.setUsername("testUser");
133         cdsProps.setPassword("testPassword");
134         cdsProps.setTimeout(1);
135
136         // Setup cdsClient
137         when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(mock(CountDownLatch.class));
138
139         // Setup onset event
140         onset = new VirtualControlLoopEvent();
141         onset.setRequestId(REQUEST_ID);
142
143         // Setup executor
144         executor = new PseudoExecutor();
145
146         target = new Target();
147         target.setType(TargetType.VM);
148         target.setResourceID(RESOURCE_ID);
149
150         cqFuture = new CompletableFuture<>();
151         when(context.obtain(eq(AaiCqResponse.CONTEXT_KEY), any())).thenReturn(cqFuture);
152         when(context.getEvent()).thenReturn(onset);
153
154         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation(GrpcOperation.NAME)
155                         .context(context).actorService(new ActorService()).targetEntity(TARGET_ENTITY).target(target)
156                         .build();
157     }
158
159     /**
160      * Tests "success" case with simulator.
161      */
162     @Test
163     public void testSuccess() throws Exception {
164         ControlLoopEventContext context = new ControlLoopEventContext(onset);
165         loadCqData(context);
166
167         Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
168
169         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation("subscribe")
170                         .context(context).actorService(new ActorService()).targetEntity(TARGET_ENTITY).target(target)
171                         .retry(0).timeoutSec(5).executor(blockingExecutor).payload(payload).build();
172
173         cdsProps.setHost("localhost");
174         cdsProps.setPort(sim.getPort());
175         cdsProps.setTimeout(3);
176
177         GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
178
179         operation = new GrpcOperation(params, config) {
180             @Override
181             protected CompletableFuture<OperationOutcome> startGuardAsync() {
182                 // indicate that guard completed successfully
183                 return CompletableFuture.completedFuture(params.makeOutcome(null));
184             }
185         };
186
187         OperationOutcome outcome = operation.start().get();
188         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
189         assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
190     }
191
192     /**
193      * Tests "success" case with simulator using properties.
194      */
195     @Test
196     public void testSuccessViaProperties() throws Exception {
197         ControlLoopEventContext context = new ControlLoopEventContext(onset);
198         loadCqData(context);
199
200         Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
201
202         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation("subscribe")
203                         .context(context).actorService(new ActorService()).targetEntity(TARGET_ENTITY).target(target)
204                         .retry(0).timeoutSec(5).executor(blockingExecutor).payload(payload).preprocessed(true).build();
205
206         cdsProps.setHost("localhost");
207         cdsProps.setPort(sim.getPort());
208         cdsProps.setTimeout(3);
209
210         GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
211
212         operation = new GrpcOperation(params, config);
213
214         // set the properties
215         operation.setProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES, Collections.emptyMap());
216
217         OperationOutcome outcome = operation.start().get();
218         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
219         assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
220     }
221
222     @Test
223     public void testGetPropertyNames() {
224
225         /*
226          * check VNF case
227          */
228         operation = new GrpcOperation(params, config);
229
230         // @formatter:off
231         assertThat(operation.getPropertyNames()).isEqualTo(
232                         List.of(
233                             OperationProperties.AAI_RESOURCE_VNF,
234                             OperationProperties.AAI_SERVICE,
235                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
236                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
237         // @formatter:on
238
239         /*
240          * check PNF case
241          */
242         target.setType(TargetType.PNF);
243         operation = new GrpcOperation(params, config);
244
245         // @formatter:off
246         assertThat(operation.getPropertyNames()).isEqualTo(
247                         List.of(
248                             OperationProperties.AAI_PNF,
249                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
250                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
251         // @formatter:on
252     }
253
254     @Test
255     public void testGetPnf() {
256         ControlLoopEventContext context = new ControlLoopEventContext(onset);
257         params = params.toBuilder().context(context).build();
258         operation = new GrpcOperation(params, config);
259
260         // in neither property nor context
261         assertThatIllegalArgumentException().isThrownBy(() -> operation.getPnfData()).withMessage("missing PNF data");
262
263         // only in context
264         Pnf pnf = new Pnf();
265         params.getContext().setProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnf);
266         assertSame(pnf, operation.getPnfData());
267
268         // both - should choose the property
269         Pnf pnf2 = new Pnf();
270         operation.setProperty(OperationProperties.AAI_PNF, pnf2);
271         assertSame(pnf2, operation.getPnfData());
272     }
273
274     @Test
275     public void testGetServiceInstanceId() {
276         ControlLoopEventContext context = new ControlLoopEventContext(onset);
277         params = params.toBuilder().context(context).build();
278         operation = new GrpcOperation(params, config);
279
280         // in neither property nor custom query
281         context.setProperty(AaiCqResponse.CONTEXT_KEY, mock(AaiCqResponse.class));
282         assertThatIllegalArgumentException().isThrownBy(() -> operation.getServiceInstanceId())
283                         .withMessage("Target service instance could not be found");
284
285         // only in custom query
286         loadCqData(params.getContext());
287         assertEquals(MY_SVC_ID, operation.getServiceInstanceId());
288
289         // both - should choose the property
290         ServiceInstance serviceInstance = new ServiceInstance();
291         serviceInstance.setServiceInstanceId("another-service-id");
292         operation.setProperty(OperationProperties.AAI_SERVICE, serviceInstance);
293         assertEquals("another-service-id", operation.getServiceInstanceId());
294     }
295
296     @Test
297     public void testGetVnfId() {
298         ControlLoopEventContext context = new ControlLoopEventContext(onset);
299         params = params.toBuilder().context(context).build();
300         operation = new GrpcOperation(params, config);
301
302         // in neither property nor custom query
303         context.setProperty(AaiCqResponse.CONTEXT_KEY, mock(AaiCqResponse.class));
304         assertThatIllegalArgumentException().isThrownBy(() -> operation.getVnfId())
305                         .withMessage("Target generic vnf could not be found");
306
307         // only in custom query
308         loadCqData(params.getContext());
309         assertEquals(MY_VNF, operation.getVnfId());
310
311         // both - should choose the property
312         GenericVnf vnf = new GenericVnf();
313         vnf.setVnfId("another-vnf-id");
314         operation.setProperty(OperationProperties.AAI_RESOURCE_VNF, vnf);
315         assertEquals("another-vnf-id", operation.getVnfId());
316     }
317
318     @Test
319     public void testStartPreprocessorAsync() throws InterruptedException, ExecutionException, TimeoutException {
320         AtomicBoolean guardStarted = new AtomicBoolean();
321
322         operation = new GrpcOperation(params, config) {
323             @Override
324             protected CompletableFuture<OperationOutcome> startGuardAsync() {
325                 guardStarted.set(true);
326                 return cqFuture;
327             }
328         };
329
330         CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
331         assertNotNull(future3);
332         assertTrue(guardStarted.get());
333         verify(context).obtain(eq(AaiCqResponse.CONTEXT_KEY), any());
334
335         cqFuture.complete(params.makeOutcome(null));
336         assertTrue(executor.runAll(100));
337         assertEquals(PolicyResult.SUCCESS, future3.get(2, TimeUnit.SECONDS).getResult());
338         assertTrue(future3.isDone());
339     }
340
341     /**
342      * Tests startPreprocessorAsync() when the target type is PNF.
343      */
344     @Test
345     public void testStartPreprocessorAsyncPnf() throws InterruptedException, ExecutionException, TimeoutException {
346         AtomicBoolean guardStarted = new AtomicBoolean();
347
348         target.setType(TargetType.PNF);
349
350         operation = new GrpcOperation(params, config) {
351             @Override
352             protected CompletableFuture<OperationOutcome> startGuardAsync() {
353                 guardStarted.set(true);
354                 return cqFuture;
355             }
356         };
357
358         CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
359         assertNotNull(future3);
360         assertTrue(guardStarted.get());
361         verify(context).obtain(eq(AaiGetPnfOperation.getKey(TARGET_ENTITY)), any());
362
363         cqFuture.complete(params.makeOutcome(null));
364         assertTrue(executor.runAll(100));
365         assertEquals(PolicyResult.SUCCESS, future3.get(2, TimeUnit.SECONDS).getResult());
366         assertTrue(future3.isDone());
367     }
368
369     /**
370      * Tests startPreprocessorAsync(), when preprocessing is disabled.
371      */
372     @Test
373     public void testStartPreprocessorAsyncDisabled() {
374         params = params.toBuilder().preprocessed(true).build();
375         assertNull(new GrpcOperation(params, config).startPreprocessorAsync());
376     }
377
378     @Test
379     public void testStartOperationAsync() throws Exception {
380
381         ControlLoopEventContext context = new ControlLoopEventContext(onset);
382         loadCqData(context);
383
384         verifyOperation(context);
385     }
386
387     /**
388      * Tests startOperationAsync() when the target type is PNF.
389      */
390     @Test
391     public void testStartOperationAsyncPnf() throws Exception {
392
393         target.setType(TargetType.PNF);
394
395         ControlLoopEventContext context = new ControlLoopEventContext(onset);
396         loadPnfData(context);
397
398         verifyOperation(context);
399     }
400
401     @Test
402     public void testStartOperationAsyncWithAdditionalParams() throws Exception {
403
404         Map<String, String> additionalParams = new HashMap<>();
405         additionalParams.put("test", "additionalParams");
406         onset.setAdditionalEventParams(additionalParams);
407         ControlLoopEventContext context = new ControlLoopEventContext(onset);
408         loadCqData(context);
409         verifyOperation(context);
410     }
411
412     @Test
413     public void testStartOperationAsyncError() throws Exception {
414         operation = new GrpcOperation(params, config);
415         assertThatIllegalArgumentException()
416                         .isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome(null)));
417     }
418
419     @Test
420     public void testGetAdditionalEventParams() {
421         operation = new GrpcOperation(params, config);
422
423         // in neither property nor context
424         assertNull(operation.getAdditionalEventParams());
425
426         final Map<String, String> eventParams = Collections.emptyMap();
427
428         // only in context
429         onset.setAdditionalEventParams(eventParams);
430         assertSame(eventParams, operation.getAdditionalEventParams());
431
432         // both - should choose the property, even if it's null
433         operation.setProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS, null);
434         assertNull(operation.getAdditionalEventParams());
435
436         // both - should choose the property
437         final Map<String, String> propParams = Collections.emptyMap();
438         operation.setProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS, propParams);
439         assertSame(propParams, operation.getAdditionalEventParams());
440     }
441
442     private void verifyOperation(ControlLoopEventContext context) {
443
444         Map<String, Object> payloadMap = Map.of(CdsActorConstants.KEY_CBA_NAME, CDS_BLUEPRINT_NAME,
445                         CdsActorConstants.KEY_CBA_VERSION, CDS_BLUEPRINT_VERSION, "data",
446                         "{\"mapInfo\":{\"key\":\"val\"},\"arrayInfo\":[\"one\",\"two\"],\"paramInfo\":\"val\"}");
447
448         ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
449                         .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
450                         .targetEntity(TARGET_ENTITY).target(target).payload(payloadMap).build();
451
452         GrpcConfig config = new GrpcConfig(executor, cdsProps);
453         operation = new GrpcOperation(params, config);
454         assertEquals(1000, operation.getTimeoutMs(null));
455         assertEquals(1000, operation.getTimeoutMs(0));
456         assertEquals(2000, operation.getTimeoutMs(2));
457         operation.generateSubRequestId(1);
458         CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome(null));
459         assertNotNull(future3);
460     }
461
462     private void loadPnfData(ControlLoopEventContext context) throws CoderException {
463         String json = "{'dataA': 'valueA', 'dataB': 'valueB'}".replace('\'', '"');
464         StandardCoderObject sco = coder.decode(json, StandardCoderObject.class);
465
466         context.setProperty(AaiGetPnfOperation.getKey(TARGET_ENTITY), sco);
467     }
468
469     private void loadCqData(ControlLoopEventContext context) {
470         GenericVnf genvnf = new GenericVnf();
471         genvnf.setVnfId(MY_VNF);
472
473         ServiceInstance serviceInstance = new ServiceInstance();
474         serviceInstance.setServiceInstanceId(MY_SVC_ID);
475
476         AaiCqResponse cq = mock(AaiCqResponse.class);
477         when(cq.getGenericVnfByModelInvariantId(any())).thenReturn(genvnf);
478         when(cq.getServiceInstance()).thenReturn(serviceInstance);
479
480         context.setProperty(AaiCqResponse.CONTEXT_KEY, cq);
481     }
482 }