2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Bell Canada. All rights reserved.
4 * Modifications Copyright (C) 2020-2021 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 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.util.JsonFormat;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.LinkedHashMap;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.UUID;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.function.Supplier;
37 import org.onap.aai.domain.yang.GenericVnf;
38 import org.onap.aai.domain.yang.ServiceInstance;
39 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
40 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
41 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
42 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
45 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
46 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
47 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
48 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
49 import org.onap.policy.controlloop.actorserviceprovider.Util;
50 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
51 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
52 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
55 * Operation that uses gRPC to send request to CDS.
59 public class GrpcOperation extends OperationPartial {
61 public static final String NAME = "any";
63 private static final String AAI_PNF_PREFIX = "pnf.";
64 private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
65 private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
67 private CdsProcessorGrpcClient client;
70 * Configuration for this operation.
72 private final GrpcConfig config;
75 * Function to convert the A&AI data associated with the target type.
77 private final Supplier<Map<String, String>> aaiConverter;
81 private static final List<String> PNF_PROPERTY_NAMES = List.of(
82 OperationProperties.AAI_PNF,
83 OperationProperties.EVENT_ADDITIONAL_PARAMS,
84 OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
87 private static final List<String> VNF_PROPERTY_NAMES = List.of(
88 OperationProperties.AAI_RESOURCE_VNF,
89 OperationProperties.AAI_SERVICE,
90 OperationProperties.EVENT_ADDITIONAL_PARAMS,
91 OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
95 * Constructs the object.
97 * @param params operation parameters
98 * @param config configuration for this operation
100 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
101 super(params, config, Collections.emptyList());
102 this.config = config;
104 if (TargetType.PNF.equals(params.getTargetType())) {
105 aaiConverter = this::convertPnfToAaiProperties;
107 aaiConverter = this::convertVnfToAaiProperties;
112 public List<String> getPropertyNames() {
113 return (TargetType.PNF.equals(params.getTargetType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
117 * If no timeout is specified, then it returns the operator's configured timeout.
120 protected long getTimeoutMs(Integer timeoutSec) {
121 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
125 * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
126 * field in the CDS request.
128 * @return a map of the PNF data
130 private Map<String, String> convertPnfToAaiProperties() {
131 Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
132 if (result != null) {
136 // convert PNF data to a Map
137 Object pnfData = getRequiredProperty(OperationProperties.AAI_PNF, "PNF");
138 Map<String, Object> source = Util.translateToMap(getFullName(), pnfData);
140 result = new LinkedHashMap<>();
142 for (Entry<String, Object> ent : source.entrySet()) {
143 result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
150 * Converts the A&AI VNF data to a map suitable for passing via the
151 * "aaiProperties" field in the CDS request.
153 * @return a map of the VNF data
155 private Map<String, String> convertVnfToAaiProperties() {
156 Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
157 if (result != null) {
161 result = new LinkedHashMap<>();
163 result.put(AAI_SERVICE_INSTANCE_ID_KEY, getServiceInstanceId());
164 result.put(AAI_VNF_ID_KEY, getVnfId());
169 protected String getServiceInstanceId() {
170 var serviceInstance = (ServiceInstance) getRequiredProperty(OperationProperties.AAI_SERVICE,
171 "Target service instance");
172 return serviceInstance.getServiceInstanceId();
175 protected String getVnfId() {
176 var genericVnf = (GenericVnf) getRequiredProperty(OperationProperties.AAI_RESOURCE_VNF, "Target generic vnf");
177 return genericVnf.getVnfId();
181 public void generateSubRequestId(int attempt) {
182 setSubRequestId("0");
189 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
192 * construct the request first so that we don't have to clean up the "client" if
193 * an exception is thrown
195 ExecutionServiceInput request = constructRequest();
197 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
199 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
200 config.getCdsServerProperties());
202 client.sendRequest(request);
204 // arrange to shutdown the client when the request completes
205 PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
207 controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
208 .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
214 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
215 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
216 * item for Frankfurt release.
218 * @return an ExecutionServiceInput instance.
220 public ExecutionServiceInput constructRequest() {
222 // For the current operational TOSCA policy model (yaml) CBA name and version are
223 // embedded in the payload
224 // section, with the new policy type model being proposed in Frankfurt we will be
225 // able to move it out.
226 if (!validateCdsMandatoryParams(params)) {
227 throw new IllegalArgumentException("missing cds mandatory params - " + params);
229 Map<String, String> payload = convertPayloadMap(params.getPayload());
230 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
231 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
233 // Retain only the payload by removing CBA name and version once they are
235 // to be put in CDS request header.
236 payload.remove(CdsActorConstants.KEY_CBA_NAME);
237 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
239 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
240 // into grpc request.
241 String cbaActionName = params.getOperation();
242 var request = new CdsActionRequest();
243 request.setPolicyPayload(payload);
244 request.setActionName(cbaActionName);
245 request.setResolutionKey(UUID.randomUUID().toString());
247 // Inject AAI properties into payload map. Offer flexibility to the usecase
248 // implementation to inject whatever AAI parameters are of interest to them.
249 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
252 // Note: that is a future enhancement. For now, the actor is hard-coded to
253 // use the A&AI query result specific to the target type
254 request.setAaiProperties(aaiConverter.get());
256 // Inject any additional event parameters that may be present in the onset event
257 Map<String, String> additionalParams = getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
258 if (additionalParams != null) {
259 request.setAdditionalEventParams(additionalParams);
262 var struct = Struct.newBuilder();
264 String requestStr = request.generateCdsPayload();
265 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
266 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
267 JsonFormat.parser().merge(requestStr, struct);
268 } catch (InvalidProtocolBufferException | CoderException e) {
269 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
270 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
273 // Build CDS gRPC request common-header
274 var commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
275 .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
277 // Build CDS gRPC request action-identifier
278 var actionIdentifiers =
279 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
280 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
282 // Finally build & return the ExecutionServiceInput gRPC request object.
283 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
284 .setPayload(struct.build()).build();
287 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
288 Map<String, String> convertedPayload = new HashMap<>();
289 for (Entry<String, Object> entry : payload.entrySet()) {
290 convertedPayload.put(entry.getKey(), entry.getValue().toString());
292 return convertedPayload;
295 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
296 if (params == null || params.getPayload() == null) {
299 Map<String, Object> payload = params.getPayload();
300 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
301 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
304 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
305 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
306 && !Strings.isNullOrEmpty(params.getOperation());