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
10 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.policy.controlloop.actor.cds;
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;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.List;
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;
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();
90 protected static final Executor blockingExecutor = command -> {
91 Thread thread = new Thread(command);
92 thread.setDaemon(true);
96 private static CdsSimulator sim;
99 private CdsProcessorGrpcClient cdsClient;
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;
112 public static void setUpBeforeClass() throws Exception {
113 sim = Util.buildCdsSim();
117 public static void tearDownAfterClass() {
122 * Sets up the fields.
125 public void setUp() throws Exception {
126 MockitoAnnotations.initMocks(this);
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);
137 when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(mock(CountDownLatch.class));
140 onset = new VirtualControlLoopEvent();
141 onset.setRequestId(REQUEST_ID);
144 executor = new PseudoExecutor();
146 target = new Target();
147 target.setType(TargetType.VM);
148 target.setResourceID(RESOURCE_ID);
150 cqFuture = new CompletableFuture<>();
151 when(context.obtain(eq(AaiCqResponse.CONTEXT_KEY), any())).thenReturn(cqFuture);
152 when(context.getEvent()).thenReturn(onset);
154 params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation(GrpcOperation.NAME)
155 .context(context).actorService(new ActorService()).targetEntity(TARGET_ENTITY).target(target)
160 * Tests "success" case with simulator.
163 public void testSuccess() throws Exception {
164 ControlLoopEventContext context = new ControlLoopEventContext(onset);
167 Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
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();
173 cdsProps.setHost("localhost");
174 cdsProps.setPort(sim.getPort());
175 cdsProps.setTimeout(3);
177 GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
179 operation = new GrpcOperation(params, config) {
181 protected CompletableFuture<OperationOutcome> startGuardAsync() {
182 // indicate that guard completed successfully
183 return CompletableFuture.completedFuture(params.makeOutcome(null));
187 OperationOutcome outcome = operation.start().get();
188 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
189 assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
193 * Tests "success" case with simulator using properties.
196 public void testSuccessViaProperties() throws Exception {
197 ControlLoopEventContext context = new ControlLoopEventContext(onset);
200 Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
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();
206 cdsProps.setHost("localhost");
207 cdsProps.setPort(sim.getPort());
208 cdsProps.setTimeout(3);
210 GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
212 operation = new GrpcOperation(params, config);
214 // set the properties
215 operation.setProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES, Collections.emptyMap());
217 OperationOutcome outcome = operation.start().get();
218 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
219 assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
223 public void testGetPropertyNames() {
228 operation = new GrpcOperation(params, config);
231 assertThat(operation.getPropertyNames()).isEqualTo(
233 OperationProperties.AAI_RESOURCE_VNF,
234 OperationProperties.AAI_SERVICE,
235 OperationProperties.EVENT_ADDITIONAL_PARAMS,
236 OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
242 target.setType(TargetType.PNF);
243 operation = new GrpcOperation(params, config);
246 assertThat(operation.getPropertyNames()).isEqualTo(
248 OperationProperties.AAI_PNF,
249 OperationProperties.EVENT_ADDITIONAL_PARAMS,
250 OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
255 public void testGetPnf() {
256 ControlLoopEventContext context = new ControlLoopEventContext(onset);
257 params = params.toBuilder().context(context).build();
258 operation = new GrpcOperation(params, config);
260 // in neither property nor context
261 assertThatIllegalArgumentException().isThrownBy(() -> operation.getPnfData()).withMessage("missing PNF data");
265 params.getContext().setProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnf);
266 assertSame(pnf, operation.getPnfData());
268 // both - should choose the property
269 Pnf pnf2 = new Pnf();
270 operation.setProperty(OperationProperties.AAI_PNF, pnf2);
271 assertSame(pnf2, operation.getPnfData());
275 public void testGetServiceInstanceId() {
276 ControlLoopEventContext context = new ControlLoopEventContext(onset);
277 params = params.toBuilder().context(context).build();
278 operation = new GrpcOperation(params, config);
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");
285 // only in custom query
286 loadCqData(params.getContext());
287 assertEquals(MY_SVC_ID, operation.getServiceInstanceId());
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());
297 public void testGetVnfId() {
298 ControlLoopEventContext context = new ControlLoopEventContext(onset);
299 params = params.toBuilder().context(context).build();
300 operation = new GrpcOperation(params, config);
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");
307 // only in custom query
308 loadCqData(params.getContext());
309 assertEquals(MY_VNF, operation.getVnfId());
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());
319 public void testStartPreprocessorAsync() throws InterruptedException, ExecutionException, TimeoutException {
320 AtomicBoolean guardStarted = new AtomicBoolean();
322 operation = new GrpcOperation(params, config) {
324 protected CompletableFuture<OperationOutcome> startGuardAsync() {
325 guardStarted.set(true);
330 CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
331 assertNotNull(future3);
332 assertTrue(guardStarted.get());
333 verify(context).obtain(eq(AaiCqResponse.CONTEXT_KEY), any());
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());
342 * Tests startPreprocessorAsync() when the target type is PNF.
345 public void testStartPreprocessorAsyncPnf() throws InterruptedException, ExecutionException, TimeoutException {
346 AtomicBoolean guardStarted = new AtomicBoolean();
348 target.setType(TargetType.PNF);
350 operation = new GrpcOperation(params, config) {
352 protected CompletableFuture<OperationOutcome> startGuardAsync() {
353 guardStarted.set(true);
358 CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
359 assertNotNull(future3);
360 assertTrue(guardStarted.get());
361 verify(context).obtain(eq(AaiGetPnfOperation.getKey(TARGET_ENTITY)), any());
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());
370 * Tests startPreprocessorAsync(), when preprocessing is disabled.
373 public void testStartPreprocessorAsyncDisabled() {
374 params = params.toBuilder().preprocessed(true).build();
375 assertNull(new GrpcOperation(params, config).startPreprocessorAsync());
379 public void testStartOperationAsync() throws Exception {
381 ControlLoopEventContext context = new ControlLoopEventContext(onset);
384 verifyOperation(context);
388 * Tests startOperationAsync() when the target type is PNF.
391 public void testStartOperationAsyncPnf() throws Exception {
393 target.setType(TargetType.PNF);
395 ControlLoopEventContext context = new ControlLoopEventContext(onset);
396 loadPnfData(context);
398 verifyOperation(context);
402 public void testStartOperationAsyncWithAdditionalParams() throws Exception {
404 Map<String, String> additionalParams = new HashMap<>();
405 additionalParams.put("test", "additionalParams");
406 onset.setAdditionalEventParams(additionalParams);
407 ControlLoopEventContext context = new ControlLoopEventContext(onset);
409 verifyOperation(context);
413 public void testStartOperationAsyncError() throws Exception {
414 operation = new GrpcOperation(params, config);
415 assertThatIllegalArgumentException()
416 .isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome(null)));
420 public void testGetAdditionalEventParams() {
421 operation = new GrpcOperation(params, config);
423 // in neither property nor context
424 assertNull(operation.getAdditionalEventParams());
426 final Map<String, String> eventParams = Collections.emptyMap();
429 onset.setAdditionalEventParams(eventParams);
430 assertSame(eventParams, operation.getAdditionalEventParams());
432 // both - should choose the property, even if it's null
433 operation.setProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS, null);
434 assertNull(operation.getAdditionalEventParams());
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());
442 private void verifyOperation(ControlLoopEventContext context) {
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\"}");
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();
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);
462 private void loadPnfData(ControlLoopEventContext context) throws CoderException {
463 String json = "{'dataA': 'valueA', 'dataB': 'valueB'}".replace('\'', '"');
464 StandardCoderObject sco = coder.decode(json, StandardCoderObject.class);
466 context.setProperty(AaiGetPnfOperation.getKey(TARGET_ENTITY), sco);
469 private void loadCqData(ControlLoopEventContext context) {
470 GenericVnf genvnf = new GenericVnf();
471 genvnf.setVnfId(MY_VNF);
473 ServiceInstance serviceInstance = new ServiceInstance();
474 serviceInstance.setServiceInstanceId(MY_SVC_ID);
476 AaiCqResponse cq = mock(AaiCqResponse.class);
477 when(cq.getGenericVnfByModelInvariantId(any())).thenReturn(genvnf);
478 when(cq.getServiceInstance()).thenReturn(serviceInstance);
480 context.setProperty(AaiCqResponse.CONTEXT_KEY, cq);