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;
29 import java.util.LinkedHashMap;
31 import java.util.Map.Entry;
32 import java.util.UUID;
33 import java.util.concurrent.CompletableFuture;
34 import java.util.function.Supplier;
36 import org.onap.aai.domain.yang.GenericVnf;
37 import org.onap.aai.domain.yang.ServiceInstance;
38 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
39 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
40 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
41 import org.onap.policy.aai.AaiConstants;
42 import org.onap.policy.aai.AaiCqResponse;
43 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
44 import org.onap.policy.common.utils.coder.CoderException;
45 import org.onap.policy.common.utils.coder.StandardCoderObject;
46 import org.onap.policy.controlloop.actor.aai.AaiCustomQueryOperation;
47 import org.onap.policy.controlloop.actor.aai.AaiGetPnfOperation;
48 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
49 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
50 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
51 import org.onap.policy.controlloop.actorserviceprovider.Util;
52 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
53 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
54 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
55 import org.onap.policy.controlloop.policy.TargetType;
58 * Operation that uses gRPC to send request to CDS.
62 public class GrpcOperation extends OperationPartial {
64 public static final String NAME = "any";
66 private static final String AAI_PNF_PREFIX = "pnf.";
67 private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
68 private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
70 private CdsProcessorGrpcClient client;
73 * Configuration for this operation.
75 private final GrpcConfig config;
78 * Function to request the A&AI data appropriate to the target type.
80 private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
83 * Function to convert the A&AI data associated with the target type.
85 private final Supplier<Map<String, String>> aaiConverter;
88 * Constructs the object.
90 * @param params operation parameters
91 * @param config configuration for this operation
93 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
94 super(params, config);
97 if (TargetType.PNF.equals(params.getTarget().getType())) {
98 aaiRequestor = this::getPnf;
99 aaiConverter = this::convertPnfToAaiProperties;
101 aaiRequestor = this::getCq;
102 aaiConverter = this::convertCqToAaiProperties;
107 * If no timeout is specified, then it returns the operator's configured timeout.
110 protected long getTimeoutMs(Integer timeoutSec) {
111 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
115 * Ensures that A&AI query has been performed, and runs the guard.
118 @SuppressWarnings("unchecked")
119 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
120 // run A&AI Query and Guard, in parallel
121 return allOf(aaiRequestor, this::startGuardAsync);
125 * Requests the A&AI PNF data.
127 * @return a future to get the PNF data
129 private CompletableFuture<OperationOutcome> getPnf() {
130 ControlLoopOperationParams pnfParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
131 .operation(AaiGetPnfOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
133 return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
137 * Requests the A&AI Custom Query data.
139 * @return a future to get the custom query data
141 private CompletableFuture<OperationOutcome> getCq() {
142 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
143 .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
145 return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
149 * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
150 * field in the CDS request.
152 * @return a map of the PNF data
154 private Map<String, String> convertPnfToAaiProperties() {
155 // convert PNF data to a Map
156 StandardCoderObject pnf = params.getContext().getProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()));
157 Map<String, Object> source = Util.translateToMap(getFullName(), pnf);
159 Map<String, String> result = new LinkedHashMap<>();
161 for (Entry<String, Object> ent : source.entrySet()) {
162 result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
169 * Converts the A&AI Custom Query data to a map suitable for passing via the
170 * "aaiProperties" field in the CDS request.
172 * @return a map of the custom query data
174 private Map<String, String> convertCqToAaiProperties() {
175 AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
177 Map<String, String> result = new LinkedHashMap<>();
179 ServiceInstance serviceInstance = aaicq.getServiceInstance();
180 if (serviceInstance == null) {
181 throw new IllegalArgumentException("Target service instance could not be found");
184 GenericVnf genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
185 if (genericVnf == null) {
186 throw new IllegalArgumentException("Target generic vnf could not be found");
189 result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId());
190 result.put(AAI_VNF_ID_KEY, genericVnf.getVnfId());
196 public void generateSubRequestId(int attempt) {
197 setSubRequestId("0");
204 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
207 * construct the request first so that we don't have to clean up the "client" if
208 * an exception is thrown
210 ExecutionServiceInput request = constructRequest(params);
212 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
214 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
215 config.getCdsServerProperties());
217 client.sendRequest(request);
219 // arrange to shutdown the client when the request completes
220 PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
222 controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
223 .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
229 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
230 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
231 * item for Frankfurt release.
233 * @param params the control loop parameters specifying the onset, payload, etc.
234 * @return an ExecutionServiceInput instance.
236 public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
238 // For the current operational TOSCA policy model (yaml) CBA name and version are
239 // embedded in the payload
240 // section, with the new policy type model being proposed in Frankfurt we will be
241 // able to move it out.
242 if (!validateCdsMandatoryParams(params)) {
243 throw new IllegalArgumentException("missing cds mandatory params - " + params);
245 Map<String, String> payload = convertPayloadMap(params.getPayload());
246 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
247 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
249 // Retain only the payload by removing CBA name and version once they are
251 // to be put in CDS request header.
252 payload.remove(CdsActorConstants.KEY_CBA_NAME);
253 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
255 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
256 // into grpc request.
257 String cbaActionName = params.getOperation();
258 CdsActionRequest request = new CdsActionRequest();
259 request.setPolicyPayload(payload);
260 request.setActionName(cbaActionName);
261 request.setResolutionKey(UUID.randomUUID().toString());
263 // Inject AAI properties into payload map. Offer flexibility to the usecase
264 // implementation to inject whatever AAI parameters are of interest to them.
265 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
268 // Note: that is a future enhancement. For now, the actor is hard-coded to
269 // use the A&AI query result specific to the target type
270 request.setAaiProperties(aaiConverter.get());
272 // Inject any additional event parameters that may be present in the onset event
273 if (params.getContext().getEvent().getAdditionalEventParams() != null) {
274 request.setAdditionalEventParams(params.getContext().getEvent().getAdditionalEventParams());
277 Builder struct = Struct.newBuilder();
279 String requestStr = request.generateCdsPayload();
280 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
281 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
282 JsonFormat.parser().merge(requestStr, struct);
283 } catch (InvalidProtocolBufferException | CoderException e) {
284 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
285 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
288 // Build CDS gRPC request common-header
289 CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
290 .setRequestId(params.getContext().getEvent().getRequestId().toString())
291 .setSubRequestId(getSubRequestId()).build();
293 // Build CDS gRPC request action-identifier
294 ActionIdentifiers actionIdentifiers =
295 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
296 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
298 // Finally build & return the ExecutionServiceInput gRPC request object.
299 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
300 .setPayload(struct.build()).build();
303 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
304 Map<String, String> convertedPayload = new HashMap<>();
305 for (Entry<String, Object> entry : payload.entrySet()) {
306 convertedPayload.put(entry.getKey(), entry.getValue().toString());
308 return convertedPayload;
311 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
312 if (params == null || params.getPayload() == null) {
315 Map<String, Object> payload = params.getPayload();
316 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
317 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
320 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
321 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
322 && !Strings.isNullOrEmpty(params.getOperation());