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
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.List;
31 import java.util.Map.Entry;
32 import java.util.UUID;
33 import java.util.concurrent.CompletableFuture;
35 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
36 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
37 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
38 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
41 import org.onap.policy.controlloop.actor.cds.properties.GrpcOperationProperties;
42 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
43 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
44 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
45 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
46 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
47 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
50 * Operation that uses gRPC to send request to CDS.
54 public class GrpcOperation extends OperationPartial {
56 public static final String NAME = "any";
58 private CdsProcessorGrpcClient client;
61 * Configuration for this operation.
63 private final GrpcConfig config;
66 * Operation properties.
68 private final GrpcOperationProperties opProperties;
71 * Constructs the object.
73 * @param params operation parameters
74 * @param config configuration for this operation
76 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
77 super(params, config, Collections.emptyList());
79 this.opProperties = GrpcOperationProperties.build(params);
83 public List<String> getPropertyNames() {
84 return this.opProperties.getPropertyNames();
88 * If no timeout is specified, then it returns the operator's configured timeout.
91 protected long getTimeoutMs(Integer timeoutSec) {
92 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
96 public void generateSubRequestId(int attempt) {
104 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
107 * construct the request first so that we don't have to clean up the "client" if
108 * an exception is thrown
110 ExecutionServiceInput request = constructRequest();
112 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
114 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
115 config.getCdsServerProperties());
117 client.sendRequest(request);
119 // arrange to shutdown the client when the request completes
120 PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
122 controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
123 .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
129 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
130 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
131 * item for Frankfurt release.
133 * @return an ExecutionServiceInput instance.
135 public ExecutionServiceInput constructRequest() {
137 // For the current operational TOSCA policy model (yaml) CBA name and version are
138 // embedded in the payload
139 // section, with the new policy type model being proposed in Frankfurt we will be
140 // able to move it out.
141 if (!validateCdsMandatoryParams(params)) {
142 throw new IllegalArgumentException("missing cds mandatory params - " + params);
144 Map<String, String> payload = convertPayloadMap(params.getPayload());
145 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
146 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
148 // Retain only the payload by removing CBA name and version once they are
150 // to be put in CDS request header.
151 payload.remove(CdsActorConstants.KEY_CBA_NAME);
152 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
154 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
155 // into grpc request.
156 String cbaActionName = params.getOperation();
157 var request = new CdsActionRequest();
158 request.setPolicyPayload(payload);
159 request.setActionName(cbaActionName);
160 request.setResolutionKey(UUID.randomUUID().toString());
162 // Inject AAI properties into payload map. Offer flexibility to the usecase
163 // implementation to inject whatever AAI parameters are of interest to them.
164 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
167 // Note: that is a future enhancement. For now, the actor is hard-coded to
168 // use the A&AI query result specific to the target type
169 request.setAaiProperties(opProperties.convertToAaiProperties(this));
171 // Inject any additional event parameters that may be present in the onset event
172 Map<String, String> additionalParams = getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
173 if (additionalParams != null) {
174 request.setAdditionalEventParams(additionalParams);
177 var struct = Struct.newBuilder();
179 String requestStr = request.generateCdsPayload();
180 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
181 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
182 JsonFormat.parser().merge(requestStr, struct);
183 } catch (InvalidProtocolBufferException | CoderException e) {
184 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
185 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
188 // Build CDS gRPC request common-header
189 var commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
190 .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
192 // Build CDS gRPC request action-identifier
193 var actionIdentifiers =
194 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
195 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
197 // Finally build & return the ExecutionServiceInput gRPC request object.
198 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
199 .setPayload(struct.build()).build();
202 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
203 Map<String, String> convertedPayload = new HashMap<>();
204 for (Entry<String, Object> entry : payload.entrySet()) {
205 convertedPayload.put(entry.getKey(), entry.getValue().toString());
207 return convertedPayload;
210 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
211 if (params == null || params.getPayload() == null) {
214 Map<String, Object> payload = params.getPayload();
215 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
216 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
219 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
220 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
221 && !Strings.isNullOrEmpty(params.getOperation());