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.aai.AaiConstants;
44 import org.onap.policy.aai.AaiCqResponse;
45 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.controlloop.actor.aai.AaiCustomQueryOperation;
48 import org.onap.policy.controlloop.actor.aai.AaiGetPnfOperation;
49 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
50 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
51 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
52 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
53 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
54 import org.onap.policy.controlloop.actorserviceprovider.Util;
55 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
56 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
57 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
60 * Operation that uses gRPC to send request to CDS.
64 public class GrpcOperation extends OperationPartial {
66 public static final String NAME = "any";
68 private static final String AAI_PNF_PREFIX = "pnf.";
69 private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
70 private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
72 private CdsProcessorGrpcClient client;
75 * Configuration for this operation.
77 private final GrpcConfig config;
80 * Function to request the A&AI data appropriate to the target type.
82 private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
85 * Function to convert the A&AI data associated with the target type.
87 private final Supplier<Map<String, String>> aaiConverter;
91 private static final List<String> PNF_PROPERTY_NAMES = List.of(
92 OperationProperties.AAI_PNF,
93 OperationProperties.EVENT_ADDITIONAL_PARAMS,
94 OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
97 private static final List<String> VNF_PROPERTY_NAMES = List.of(
98 OperationProperties.AAI_RESOURCE_VNF,
99 OperationProperties.AAI_SERVICE,
100 OperationProperties.EVENT_ADDITIONAL_PARAMS,
101 OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
105 * Constructs the object.
107 * @param params operation parameters
108 * @param config configuration for this operation
110 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
111 super(params, config, Collections.emptyList());
112 this.config = config;
114 if (TargetType.PNF.equals(params.getTargetType())) {
115 aaiRequestor = this::getPnf;
116 aaiConverter = this::convertPnfToAaiProperties;
118 aaiRequestor = this::getCq;
119 aaiConverter = this::convertCqToAaiProperties;
124 public List<String> getPropertyNames() {
125 return (TargetType.PNF.equals(params.getTargetType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
129 * If no timeout is specified, then it returns the operator's configured timeout.
132 protected long getTimeoutMs(Integer timeoutSec) {
133 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
137 * Ensures that A&AI query has been performed, and runs the guard.
140 @SuppressWarnings("unchecked")
141 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
142 if (params.isPreprocessed()) {
146 // run A&AI Query and Guard, in parallel
147 return allOf(aaiRequestor, this::startGuardAsync);
151 * Requests the A&AI PNF data.
153 * @return a future to get the PNF data
155 private CompletableFuture<OperationOutcome> getPnf() {
156 ControlLoopOperationParams pnfParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
157 .operation(AaiGetPnfOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
159 return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
163 * Requests the A&AI Custom Query data.
165 * @return a future to get the custom query data
167 private CompletableFuture<OperationOutcome> getCq() {
168 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
169 .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
171 return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
175 * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
176 * field in the CDS request.
178 * @return a map of the PNF data
180 private Map<String, String> convertPnfToAaiProperties() {
181 Map<String, String> result = this.getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
182 if (result != null) {
186 // convert PNF data to a Map
187 Map<String, Object> source = Util.translateToMap(getFullName(), getPnfData());
189 result = new LinkedHashMap<>();
191 for (Entry<String, Object> ent : source.entrySet()) {
192 result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
199 * Gets the PNF from the operation properties, if it exists, or from the context
200 * properties otherwise.
202 * @return the PNF item
204 protected Object getPnfData() {
205 Object pnf = getProperty(OperationProperties.AAI_PNF);
210 pnf = params.getContext().getProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()));
212 throw new IllegalArgumentException("missing PNF data");
219 * Converts the A&AI Custom Query data to a map suitable for passing via the
220 * "aaiProperties" field in the CDS request.
222 * @return a map of the custom query data
224 private Map<String, String> convertCqToAaiProperties() {
225 Map<String, String> result = this.getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
226 if (result != null) {
230 result = new LinkedHashMap<>();
232 result.put(AAI_SERVICE_INSTANCE_ID_KEY, getServiceInstanceId());
233 result.put(AAI_VNF_ID_KEY, getVnfId());
238 protected String getServiceInstanceId() {
239 ServiceInstance serviceInstance = getProperty(OperationProperties.AAI_SERVICE);
240 if (serviceInstance != null) {
241 return serviceInstance.getServiceInstanceId();
244 AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
246 serviceInstance = aaicq.getServiceInstance();
247 if (serviceInstance == null) {
248 throw new IllegalArgumentException("Target service instance could not be found");
251 return serviceInstance.getServiceInstanceId();
254 protected String getVnfId() {
255 GenericVnf genericVnf = getProperty(OperationProperties.AAI_RESOURCE_VNF);
256 if (genericVnf != null) {
257 return genericVnf.getVnfId();
260 AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
262 genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTargetEntityIds()
263 .get(ControlLoopOperationParams.PARAMS_ENTITY_RESOURCEID));
264 if (genericVnf == null) {
265 throw new IllegalArgumentException("Target generic vnf could not be found");
268 return genericVnf.getVnfId();
272 public void generateSubRequestId(int attempt) {
273 setSubRequestId("0");
280 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
283 * construct the request first so that we don't have to clean up the "client" if
284 * an exception is thrown
286 ExecutionServiceInput request = constructRequest();
288 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
290 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
291 config.getCdsServerProperties());
293 client.sendRequest(request);
295 // arrange to shutdown the client when the request completes
296 PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
298 controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
299 .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
305 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
306 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
307 * item for Frankfurt release.
309 * @return an ExecutionServiceInput instance.
311 public ExecutionServiceInput constructRequest() {
313 // For the current operational TOSCA policy model (yaml) CBA name and version are
314 // embedded in the payload
315 // section, with the new policy type model being proposed in Frankfurt we will be
316 // able to move it out.
317 if (!validateCdsMandatoryParams(params)) {
318 throw new IllegalArgumentException("missing cds mandatory params - " + params);
320 Map<String, String> payload = convertPayloadMap(params.getPayload());
321 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
322 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
324 // Retain only the payload by removing CBA name and version once they are
326 // to be put in CDS request header.
327 payload.remove(CdsActorConstants.KEY_CBA_NAME);
328 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
330 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
331 // into grpc request.
332 String cbaActionName = params.getOperation();
333 CdsActionRequest request = new CdsActionRequest();
334 request.setPolicyPayload(payload);
335 request.setActionName(cbaActionName);
336 request.setResolutionKey(UUID.randomUUID().toString());
338 // Inject AAI properties into payload map. Offer flexibility to the usecase
339 // implementation to inject whatever AAI parameters are of interest to them.
340 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
343 // Note: that is a future enhancement. For now, the actor is hard-coded to
344 // use the A&AI query result specific to the target type
345 request.setAaiProperties(aaiConverter.get());
347 // Inject any additional event parameters that may be present in the onset event
348 Map<String, String> additionalParams = getAdditionalEventParams();
349 if (additionalParams != null) {
350 request.setAdditionalEventParams(additionalParams);
353 Builder struct = Struct.newBuilder();
355 String requestStr = request.generateCdsPayload();
356 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
357 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
358 JsonFormat.parser().merge(requestStr, struct);
359 } catch (InvalidProtocolBufferException | CoderException e) {
360 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
361 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
364 // Build CDS gRPC request common-header
365 CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
366 .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
368 // Build CDS gRPC request action-identifier
369 ActionIdentifiers actionIdentifiers =
370 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
371 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
373 // Finally build & return the ExecutionServiceInput gRPC request object.
374 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
375 .setPayload(struct.build()).build();
378 protected Map<String, String> getAdditionalEventParams() {
379 if (containsProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS)) {
380 return getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
383 return params.getContext().getEvent().getAdditionalEventParams();
386 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
387 Map<String, String> convertedPayload = new HashMap<>();
388 for (Entry<String, Object> entry : payload.entrySet()) {
389 convertedPayload.put(entry.getKey(), entry.getValue().toString());
391 return convertedPayload;
394 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
395 if (params == null || params.getPayload() == null) {
398 Map<String, Object> payload = params.getPayload();
399 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
400 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
403 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
404 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
405 && !Strings.isNullOrEmpty(params.getOperation());