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