Set all cross references of policy/models
[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-2022 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.assertj.core.api.Assertions.assertThatIllegalStateException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertTrue;
28
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.UUID;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.concurrent.Executor;
36 import org.junit.AfterClass;
37 import org.junit.Before;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.junit.runner.RunWith;
41 import org.mockito.Mock;
42 import org.mockito.junit.MockitoJUnitRunner;
43 import org.onap.aai.domain.yang.GenericVnf;
44 import org.onap.aai.domain.yang.ServiceInstance;
45 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
46 import org.onap.policy.cds.properties.CdsServerProperties;
47 import org.onap.policy.common.utils.coder.Coder;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.common.utils.coder.StandardCoderObject;
51 import org.onap.policy.common.utils.time.PseudoExecutor;
52 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
53 import org.onap.policy.controlloop.actor.cds.properties.GrpcOperationProperties;
54 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
55 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
56 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
57 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
58 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
59 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
60 import org.onap.policy.simulators.CdsSimulator;
61 import org.onap.policy.simulators.Util;
62
63 @RunWith(MockitoJUnitRunner.class)
64 public class GrpcOperationTest {
65     private static final String MY_VNF = "my-vnf";
66     private static final String MY_SVC_ID = "my-service-instance-id";
67     private static final String RESOURCE_ID = "my-resource-id";
68     private static final String CDS_BLUEPRINT_NAME = "vfw-cds";
69     private static final String CDS_BLUEPRINT_VERSION = "1.0.0";
70     private static final UUID REQUEST_ID = UUID.randomUUID();
71     private static final Coder coder = new StandardCoder();
72
73     protected static final Executor blockingExecutor = command -> {
74         Thread thread = new Thread(command);
75         thread.setDaemon(true);
76         thread.start();
77     };
78
79     private static CdsSimulator sim;
80
81     @Mock
82     private CdsServerProperties cdsProps;
83     private PseudoExecutor executor;
84     private Map<String, String> targetEntityIds;
85     private ControlLoopOperationParams params;
86     private GrpcConfig config;
87     private GrpcOperation operation;
88
89     @BeforeClass
90     public static void setUpBeforeClass() throws Exception {
91         sim = Util.buildCdsSim();
92     }
93
94     @AfterClass
95     public static void tearDownAfterClass() {
96         sim.stop();
97     }
98
99     /**
100      * Sets up the fields.
101      */
102     @Before
103     public void setUp() {
104         // Setup the CDS properties
105         cdsProps = new CdsServerProperties();
106         cdsProps.setHost("10.10.10.10");
107         cdsProps.setPort(2000);
108         cdsProps.setUsername("testUser");
109         cdsProps.setPassword("testPassword");
110         cdsProps.setTimeout(1);
111
112         // Setup executor
113         executor = new PseudoExecutor();
114
115         targetEntityIds = new HashMap<>();
116         targetEntityIds.put(ControlLoopOperationParams.PARAMS_ENTITY_RESOURCEID, RESOURCE_ID);
117
118         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation(GrpcOperation.NAME)
119                         .requestId(REQUEST_ID).actorService(new ActorService())
120                         .build();
121     }
122
123     /**
124      * Tests "success" case with simulator.
125      */
126     @Test
127     public void testSuccess() throws Exception {
128         Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
129
130         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation("subscribe")
131                         .requestId(REQUEST_ID).actorService(new ActorService())
132                         .retry(0).timeoutSec(5).executor(blockingExecutor).payload(payload)
133                         .build();
134
135         cdsProps.setHost("localhost");
136         cdsProps.setPort(sim.getPort());
137         cdsProps.setTimeout(3);
138
139         GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
140
141         operation = new GrpcOperation(params, config);
142
143         // set the properties
144         operation.setProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES, Collections.emptyMap());
145
146         OperationOutcome outcome = operation.start().get();
147         assertEquals(OperationResult.SUCCESS, outcome.getResult());
148         assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
149     }
150
151     @Test
152     public void testGetPropertyNames() {
153         /*
154          * check VNF case with target entities
155          */
156         params = params.toBuilder().targetType(TargetType.VNF).targetEntityIds(targetEntityIds).build();
157         operation = new GrpcOperation(params, config);
158
159         // @formatter:off
160         assertThat(operation.getPropertyNames()).isEqualTo(
161                 List.of(
162                         OperationProperties.AAI_RESOURCE_VNF,
163                         OperationProperties.AAI_SERVICE,
164                         OperationProperties.EVENT_ADDITIONAL_PARAMS,
165                         OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
166         // @formatter:on
167
168         /*
169          * check VNF case with no target entities
170          */
171         params = params.toBuilder().targetEntityIds(null).build();
172         operation = new GrpcOperation(params, config);
173
174         // @formatter:off
175         assertThat(operation.getPropertyNames()).isEqualTo(
176                 List.of(
177                         OperationProperties.AAI_TARGET_ENTITY,
178                         OperationProperties.EVENT_ADDITIONAL_PARAMS,
179                         OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
180         // @formatter:on
181
182         /*
183          * check PNF case
184          */
185         params = params.toBuilder().targetType(TargetType.PNF).build();
186         operation = new GrpcOperation(params, config);
187
188         // @formatter:off
189         assertThat(operation.getPropertyNames()).isEqualTo(
190                         List.of(
191                             OperationProperties.AAI_PNF,
192                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
193                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
194         // @formatter:on
195     }
196
197     @Test
198     public void testGetServiceInstanceId() {
199         params = params.toBuilder().targetType(TargetType.VNF).targetEntityIds(targetEntityIds).build();
200         operation = new GrpcOperation(params, config);
201         loadVnfData();
202         assertEquals(MY_SVC_ID,
203             operation.getOpProperties()
204                     .convertToAaiProperties(operation)
205                     .get(GrpcOperationProperties.AAI_SERVICE_INSTANCE_ID_KEY));
206     }
207
208     @Test
209     public void testGetVnfId() {
210         params = params.toBuilder().targetType(TargetType.VNF).targetEntityIds(targetEntityIds).build();
211         operation = new GrpcOperation(params, config);
212         loadVnfData();
213         assertEquals(MY_VNF,
214             operation.getOpProperties()
215                     .convertToAaiProperties(operation)
216                     .get(GrpcOperationProperties.AAI_VNF_ID_KEY));
217
218         params = params.toBuilder().targetEntityIds(null).build();
219         operation = new GrpcOperation(params, config);
220         assertThatIllegalStateException().isThrownBy(()
221             -> operation.getOpProperties()
222                        .convertToAaiProperties(operation)
223                        .get(GrpcOperationProperties.AAI_VNF_ID_KEY));
224
225         operation.setProperty(OperationProperties.AAI_TARGET_ENTITY, MY_VNF);
226         assertEquals(MY_VNF,
227                 operation.getOpProperties()
228                         .convertToAaiProperties(operation)
229                         .get(GrpcOperationProperties.AAI_VNF_ID_KEY));
230         operation.setProperty(OperationProperties.AAI_TARGET_ENTITY, null);
231     }
232
233     @Test
234     public void testStartOperationAsync() {
235         ControlLoopOperationParams clop =
236                 ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
237                         .operation(GrpcOperation.NAME)
238                         .requestId(REQUEST_ID)
239                         .actorService(new ActorService())
240                         .targetType(TargetType.VNF)
241                         .build();
242
243         verifyOperation(clop, () -> operation.setProperty(OperationProperties.AAI_TARGET_ENTITY, MY_VNF));
244         verifyOperation(clop.toBuilder().targetEntityIds(targetEntityIds).build(), this::loadVnfData);
245     }
246
247     /**
248      * Tests startOperationAsync() when the target type is PNF.
249      */
250     @Test
251     public void testStartOperationAsyncPnf() {
252         ControlLoopOperationParams clop =
253                 ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
254                         .operation(GrpcOperation.NAME)
255                         .requestId(REQUEST_ID)
256                         .actorService(new ActorService())
257                         .targetType(TargetType.PNF)
258                         .build();
259
260         verifyOperation(clop, this::loadPnfData);
261     }
262
263     @Test
264     public void testStartOperationAsyncError() {
265         operation = new GrpcOperation(params, config);
266         assertThatIllegalArgumentException()
267                         .isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome()));
268     }
269
270     private void verifyOperation(ControlLoopOperationParams clop, Runnable loader) {
271         Map<String, Object> payloadMap = Map.of(CdsActorConstants.KEY_CBA_NAME, CDS_BLUEPRINT_NAME,
272                         CdsActorConstants.KEY_CBA_VERSION, CDS_BLUEPRINT_VERSION, "data",
273                         "{\"mapInfo\":{\"key\":\"val\"},\"arrayInfo\":[\"one\",\"two\"],\"paramInfo\":\"val\"}");
274         params = clop.toBuilder().payload(payloadMap).build();
275
276         GrpcConfig config = new GrpcConfig(executor, cdsProps);
277         operation = new GrpcOperation(params, config);
278         assertEquals(1000, operation.getTimeoutMs(null));
279         assertEquals(1000, operation.getTimeoutMs(0));
280         assertEquals(2000, operation.getTimeoutMs(2));
281         operation.generateSubRequestId(1);
282
283         loader.run();
284         CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome());
285         assertNotNull(future3);
286     }
287
288     private void loadPnfData() {
289         try {
290             String json = "{'dataA': 'valueA', 'dataB': 'valueB'}".replace('\'', '"');
291             StandardCoderObject sco = coder.decode(json, StandardCoderObject.class);
292
293             operation.setProperty(OperationProperties.AAI_PNF, sco);
294
295         } catch (CoderException e) {
296             throw new IllegalArgumentException("cannot decode PNF json", e);
297         }
298     }
299
300     private void loadVnfData() {
301         GenericVnf genvnf = new GenericVnf();
302         genvnf.setVnfId(MY_VNF);
303         operation.setProperty(OperationProperties.AAI_RESOURCE_VNF, genvnf);
304
305         ServiceInstance serviceInstance = new ServiceInstance();
306         serviceInstance.setServiceInstanceId(MY_SVC_ID);
307         operation.setProperty(OperationProperties.AAI_SERVICE, serviceInstance);
308     }
309 }