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 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;
33 import java.util.Map.Entry;
34 import java.util.UUID;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.function.Supplier;
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;
56 * Operation that uses gRPC to send request to CDS.
60 public class GrpcOperation extends OperationPartial {
62 public static final String NAME = "any";
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";
68 private CdsProcessorGrpcClient client;
71 * Configuration for this operation.
73 private final GrpcConfig config;
76 * Function to convert the A&AI data associated with the target type.
78 private final Supplier<Map<String, String>> aaiConverter;
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);
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);
96 * Constructs the object.
98 * @param params operation parameters
99 * @param config configuration for this operation
101 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
102 super(params, config, Collections.emptyList());
103 this.config = config;
105 if (TargetType.PNF.equals(params.getTargetType())) {
106 aaiConverter = this::convertPnfToAaiProperties;
108 aaiConverter = this::convertVnfToAaiProperties;
113 public List<String> getPropertyNames() {
114 return (TargetType.PNF.equals(params.getTargetType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
118 * If no timeout is specified, then it returns the operator's configured timeout.
121 protected long getTimeoutMs(Integer timeoutSec) {
122 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
126 * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
127 * field in the CDS request.
129 * @return a map of the PNF data
131 private Map<String, String> convertPnfToAaiProperties() {
132 Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
133 if (result != null) {
137 // convert PNF data to a Map
138 Object pnfData = getRequiredProperty(OperationProperties.AAI_PNF, "PNF");
139 Map<String, Object> source = Util.translateToMap(getFullName(), pnfData);
141 result = new LinkedHashMap<>();
143 for (Entry<String, Object> ent : source.entrySet()) {
144 result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
151 * Converts the A&AI VNF data to a map suitable for passing via the
152 * "aaiProperties" field in the CDS request.
154 * @return a map of the VNF data
156 private Map<String, String> convertVnfToAaiProperties() {
157 Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
158 if (result != null) {
162 result = new LinkedHashMap<>();
164 result.put(AAI_SERVICE_INSTANCE_ID_KEY, getServiceInstanceId());
165 result.put(AAI_VNF_ID_KEY, getVnfId());
170 protected String getServiceInstanceId() {
171 ServiceInstance serviceInstance =
172 getRequiredProperty(OperationProperties.AAI_SERVICE, "Target service instance");
173 return serviceInstance.getServiceInstanceId();
176 protected String getVnfId() {
177 GenericVnf genericVnf = getRequiredProperty(OperationProperties.AAI_RESOURCE_VNF, "Target generic vnf");
178 return genericVnf.getVnfId();
182 public void generateSubRequestId(int attempt) {
183 setSubRequestId("0");
190 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
193 * construct the request first so that we don't have to clean up the "client" if
194 * an exception is thrown
196 ExecutionServiceInput request = constructRequest();
198 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
200 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
201 config.getCdsServerProperties());
203 client.sendRequest(request);
205 // arrange to shutdown the client when the request completes
206 PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
208 controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
209 .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
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.
219 * @return an ExecutionServiceInput instance.
221 public ExecutionServiceInput constructRequest() {
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);
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);
234 // Retain only the payload by removing CBA name and version once they are
236 // to be put in CDS request header.
237 payload.remove(CdsActorConstants.KEY_CBA_NAME);
238 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
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());
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
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());
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);
263 Builder struct = Struct.newBuilder();
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);
274 // Build CDS gRPC request common-header
275 CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
276 .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
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();
283 // Finally build & return the ExecutionServiceInput gRPC request object.
284 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
285 .setPayload(struct.build()).build();
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());
293 return convertedPayload;
296 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
297 if (params == null || params.getPayload() == null) {
300 Map<String, Object> payload = params.getPayload();
301 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
302 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
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());