Fix sonars in policy models
[policy/models.git] / models-interactions / model-actors / actor.cds / src / main / java / org / onap / policy / controlloop / actor / cds / GrpcOperation.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 com.google.common.base.Preconditions;
23 import com.google.common.base.Strings;
24 import com.google.protobuf.InvalidProtocolBufferException;
25 import com.google.protobuf.Struct;
26 import com.google.protobuf.Struct.Builder;
27 import com.google.protobuf.util.JsonFormat;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.UUID;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.function.Supplier;
37 import lombok.Getter;
38 import org.onap.aai.domain.yang.GenericVnf;
39 import org.onap.aai.domain.yang.ServiceInstance;
40 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
41 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
42 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
43 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
44 import org.onap.policy.common.utils.coder.CoderException;
45 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
46 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
47 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
48 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
49 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
50 import org.onap.policy.controlloop.actorserviceprovider.Util;
51 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
52 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
53 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
54
55 /**
56  * Operation that uses gRPC to send request to CDS.
57  *
58  */
59 @Getter
60 public class GrpcOperation extends OperationPartial {
61
62     public static final String NAME = "any";
63
64     private static final String AAI_PNF_PREFIX = "pnf.";
65     private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
66     private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
67
68     private CdsProcessorGrpcClient client;
69
70     /**
71      * Configuration for this operation.
72      */
73     private final GrpcConfig config;
74
75     /**
76      * Function to convert the A&AI data associated with the target type.
77      */
78     private final Supplier<Map<String, String>> aaiConverter;
79
80
81     // @formatter:off
82     private static final List<String> PNF_PROPERTY_NAMES = List.of(
83                             OperationProperties.AAI_PNF,
84                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
85                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
86
87
88     private static final List<String> VNF_PROPERTY_NAMES = List.of(
89                             OperationProperties.AAI_RESOURCE_VNF,
90                             OperationProperties.AAI_SERVICE,
91                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
92                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
93     // @formatter:on
94
95     /**
96      * Constructs the object.
97      *
98      * @param params operation parameters
99      * @param config configuration for this operation
100      */
101     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
102         super(params, config, Collections.emptyList());
103         this.config = config;
104
105         if (TargetType.PNF.equals(params.getTargetType())) {
106             aaiConverter = this::convertPnfToAaiProperties;
107         } else {
108             aaiConverter = this::convertVnfToAaiProperties;
109         }
110     }
111
112     @Override
113     public List<String> getPropertyNames() {
114         return (TargetType.PNF.equals(params.getTargetType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
115     }
116
117     /**
118      * If no timeout is specified, then it returns the operator's configured timeout.
119      */
120     @Override
121     protected long getTimeoutMs(Integer timeoutSec) {
122         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
123     }
124
125     /**
126      * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
127      * field in the CDS request.
128      *
129      * @return a map of the PNF data
130      */
131     private Map<String, String> convertPnfToAaiProperties() {
132         Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
133         if (result != null) {
134             return result;
135         }
136
137         // convert PNF data to a Map
138         Object pnfData = getRequiredProperty(OperationProperties.AAI_PNF, "PNF");
139         Map<String, Object> source = Util.translateToMap(getFullName(), pnfData);
140
141         result = new LinkedHashMap<>();
142
143         for (Entry<String, Object> ent : source.entrySet()) {
144             result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
145         }
146
147         return result;
148     }
149
150     /**
151      * Converts the A&AI VNF data to a map suitable for passing via the
152      * "aaiProperties" field in the CDS request.
153      *
154      * @return a map of the VNF data
155      */
156     private Map<String, String> convertVnfToAaiProperties() {
157         Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
158         if (result != null) {
159             return result;
160         }
161
162         result = new LinkedHashMap<>();
163
164         result.put(AAI_SERVICE_INSTANCE_ID_KEY, getServiceInstanceId());
165         result.put(AAI_VNF_ID_KEY, getVnfId());
166
167         return result;
168     }
169
170     protected String getServiceInstanceId() {
171         ServiceInstance serviceInstance =
172                         getRequiredProperty(OperationProperties.AAI_SERVICE, "Target service instance");
173         return serviceInstance.getServiceInstanceId();
174     }
175
176     protected String getVnfId() {
177         GenericVnf genericVnf = getRequiredProperty(OperationProperties.AAI_RESOURCE_VNF, "Target generic vnf");
178         return genericVnf.getVnfId();
179     }
180
181     @Override
182     public void generateSubRequestId(int attempt) {
183         setSubRequestId("0");
184     }
185
186     /**
187      * {@inheritDoc}.
188      */
189     @Override
190     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
191
192         /*
193          * construct the request first so that we don't have to clean up the "client" if
194          * an exception is thrown
195          */
196         ExecutionServiceInput request = constructRequest();
197
198         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
199
200         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
201                         config.getCdsServerProperties());
202
203         client.sendRequest(request);
204
205         // arrange to shutdown the client when the request completes
206         PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
207
208         controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
209                         .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
210
211         return controller;
212     }
213
214     /**
215      * Build the CDS ExecutionServiceInput request from the policy object and the AAI
216      * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
217      * item for Frankfurt release.
218      *
219      * @return an ExecutionServiceInput instance.
220      */
221     public ExecutionServiceInput constructRequest() {
222
223         // For the current operational TOSCA policy model (yaml) CBA name and version are
224         // embedded in the payload
225         // section, with the new policy type model being proposed in Frankfurt we will be
226         // able to move it out.
227         if (!validateCdsMandatoryParams(params)) {
228             throw new IllegalArgumentException("missing cds mandatory params -  " + params);
229         }
230         Map<String, String> payload = convertPayloadMap(params.getPayload());
231         String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
232         String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
233
234         // Retain only the payload by removing CBA name and version once they are
235         // extracted
236         // to be put in CDS request header.
237         payload.remove(CdsActorConstants.KEY_CBA_NAME);
238         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
239
240         // Embed payload from policy to ConfigDeployRequest object, serialize and inject
241         // into grpc request.
242         String cbaActionName = params.getOperation();
243         CdsActionRequest request = new CdsActionRequest();
244         request.setPolicyPayload(payload);
245         request.setActionName(cbaActionName);
246         request.setResolutionKey(UUID.randomUUID().toString());
247
248         // Inject AAI properties into payload map. Offer flexibility to the usecase
249         // implementation to inject whatever AAI parameters are of interest to them.
250         // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
251         // needed by CDS.
252         //
253         // Note: that is a future enhancement. For now, the actor is hard-coded to
254         // use the A&AI query result specific to the target type
255         request.setAaiProperties(aaiConverter.get());
256
257         // Inject any additional event parameters that may be present in the onset event
258         Map<String, String> additionalParams = getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
259         if (additionalParams != null) {
260             request.setAdditionalEventParams(additionalParams);
261         }
262
263         Builder struct = Struct.newBuilder();
264         try {
265             String requestStr = request.generateCdsPayload();
266             Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
267                             "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
268             JsonFormat.parser().merge(requestStr, struct);
269         } catch (InvalidProtocolBufferException | CoderException e) {
270             throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
271                             + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
272         }
273
274         // Build CDS gRPC request common-header
275         CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
276                         .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
277
278         // Build CDS gRPC request action-identifier
279         ActionIdentifiers actionIdentifiers =
280                         ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
281                                         .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
282
283         // Finally build & return the ExecutionServiceInput gRPC request object.
284         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
285                         .setPayload(struct.build()).build();
286     }
287
288     private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
289         Map<String, String> convertedPayload = new HashMap<>();
290         for (Entry<String, Object> entry : payload.entrySet()) {
291             convertedPayload.put(entry.getKey(), entry.getValue().toString());
292         }
293         return convertedPayload;
294     }
295
296     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
297         if (params == null || params.getPayload() == null) {
298             return false;
299         }
300         Map<String, Object> payload = params.getPayload();
301         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
302                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
303             return false;
304         }
305         return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
306                         && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
307                         && !Strings.isNullOrEmpty(params.getOperation());
308     }
309 }