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.HashMap;
30 import java.util.Map.Entry;
31 import java.util.UUID;
32 import java.util.concurrent.CompletableFuture;
34 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
35 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
36 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
37 import org.onap.policy.aai.AaiConstants;
38 import org.onap.policy.aai.AaiCqResponse;
39 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
40 import org.onap.policy.common.utils.coder.CoderException;
41 import org.onap.policy.controlloop.actor.aai.AaiCustomQueryOperation;
42 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
43 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
44 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
45 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
46 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
49 * Operation that uses gRPC to send request to CDS.
53 public class GrpcOperation extends OperationPartial {
55 public static final String NAME = "any";
57 private CdsProcessorGrpcClient client;
60 * Configuration for this operation.
62 private final GrpcConfig config;
65 * Constructs the object.
67 * @param params operation parameters
68 * @param config configuration for this operation
70 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
71 super(params, config);
76 * If no timeout is specified, then it returns the operator's configured timeout.
79 protected long getTimeoutMs(Integer timeoutSec) {
80 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
84 * Ensures that A&AI customer query has been performed.
87 @SuppressWarnings("unchecked")
88 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
89 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
90 .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
92 // run Custom Query and Guard, in parallel
93 return allOf(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::startGuardAsync);
97 public void generateSubRequestId(int attempt) {
105 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
107 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
108 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
109 config.getCdsServerProperties());
111 ExecutionServiceInput request = constructRequest(params);
112 client.sendRequest(request);
117 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
118 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
119 * item for Frankfurt release.
121 * @param params the control loop parameters specifying the onset, payload, etc.
122 * @return an ExecutionServiceInput instance.
124 public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
126 // For the current operational TOSCA policy model (yaml) CBA name and version are
127 // embedded in the payload
128 // section, with the new policy type model being proposed in Frankfurt we will be
129 // able to move it out.
130 if (!validateCdsMandatoryParams(params)) {
131 throw new IllegalArgumentException("missing cds mandatory params - " + params);
133 Map<String, String> payload = convertPayloadMap(params.getPayload());
134 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
135 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
137 // Retain only the payload by removing CBA name and version once they are
139 // to be put in CDS request header.
140 payload.remove(CdsActorConstants.KEY_CBA_NAME);
141 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
143 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
144 // into grpc request.
145 String cbaActionName = params.getOperation();
146 CdsActionRequest request = new CdsActionRequest();
147 request.setPolicyPayload(payload);
148 request.setActionName(cbaActionName);
149 request.setResolutionKey(UUID.randomUUID().toString());
151 // Inject AAI properties into payload map. Offer flexibility to the usecase
152 // implementation to inject whatever AAI parameters are of interest to them.
153 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
155 request.setAaiProperties(params.getContext().getEnrichment());
157 // Inject any additional event parameters that may be present in the onset event
158 if (params.getContext().getEvent().getAdditionalEventParams() != null) {
159 request.setAdditionalEventParams(params.getContext().getEvent().getAdditionalEventParams());
162 Builder struct = Struct.newBuilder();
164 String requestStr = request.generateCdsPayload();
165 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
166 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
167 JsonFormat.parser().merge(requestStr, struct);
168 } catch (InvalidProtocolBufferException | CoderException e) {
169 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
170 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
173 // Build CDS gRPC request common-header
174 CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
175 .setRequestId(params.getContext().getEvent().getRequestId().toString())
176 .setSubRequestId(getSubRequestId()).build();
178 // Build CDS gRPC request action-identifier
179 ActionIdentifiers actionIdentifiers =
180 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
181 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
183 // Finally build & return the ExecutionServiceInput gRPC request object.
184 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
185 .setPayload(struct.build()).build();
188 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
189 Map<String, String> convertedPayload = new HashMap<>();
190 for (Entry<String, Object> entry : payload.entrySet()) {
191 convertedPayload.put(entry.getKey(), entry.getValue().toString());
193 return convertedPayload;
196 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
197 if (params == null || params.getPayload() == null) {
200 Map<String, Object> payload = params.getPayload();
201 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
202 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
205 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
206 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
207 && !Strings.isNullOrEmpty(params.getOperation());