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.common.utils.coder.StandardCoderObject;
48 import org.onap.policy.controlloop.actor.aai.AaiCustomQueryOperation;
49 import org.onap.policy.controlloop.actor.aai.AaiGetPnfOperation;
50 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
51 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
52 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
53 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
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;
58 import org.onap.policy.controlloop.policy.TargetType;
61 * Operation that uses gRPC to send request to CDS.
65 public class GrpcOperation extends OperationPartial {
67 public static final String NAME = "any";
69 private static final String AAI_PNF_PREFIX = "pnf.";
70 private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
71 private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
73 private CdsProcessorGrpcClient client;
76 * Configuration for this operation.
78 private final GrpcConfig config;
81 * Function to request the A&AI data appropriate to the target type.
83 private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
86 * Function to convert the A&AI data associated with the target type.
88 private final Supplier<Map<String, String>> aaiConverter;
92 private static final List<String> PNF_PROPERTY_NAMES = List.of(
93 OperationProperties.AAI_PNF,
94 OperationProperties.EVENT_ADDITIONAL_PARAMS);
97 private static final List<String> VNF_PROPERTY_NAMES = List.of(
98 OperationProperties.AAI_MODEL_INVARIANT_GENERIC_VNF,
99 OperationProperties.AAI_RESOURCE_SERVICE_INSTANCE,
100 OperationProperties.EVENT_ADDITIONAL_PARAMS);
104 * Constructs the object.
106 * @param params operation parameters
107 * @param config configuration for this operation
109 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
110 super(params, config, Collections.emptyList());
111 this.config = config;
113 if (TargetType.PNF.equals(params.getTarget().getType())) {
114 aaiRequestor = this::getPnf;
115 aaiConverter = this::convertPnfToAaiProperties;
117 aaiRequestor = this::getCq;
118 aaiConverter = this::convertCqToAaiProperties;
123 public List<String> getPropertyNames() {
124 return (TargetType.PNF.equals(params.getTarget().getType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
128 * If no timeout is specified, then it returns the operator's configured timeout.
131 protected long getTimeoutMs(Integer timeoutSec) {
132 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
136 * Ensures that A&AI query has been performed, and runs the guard.
139 @SuppressWarnings("unchecked")
140 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
141 // run A&AI Query and Guard, in parallel
142 return allOf(aaiRequestor, this::startGuardAsync);
146 * Requests the A&AI PNF data.
148 * @return a future to get the PNF data
150 private CompletableFuture<OperationOutcome> getPnf() {
151 ControlLoopOperationParams pnfParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
152 .operation(AaiGetPnfOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
154 return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
158 * Requests the A&AI Custom Query data.
160 * @return a future to get the custom query data
162 private CompletableFuture<OperationOutcome> getCq() {
163 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
164 .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
166 return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
170 * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
171 * field in the CDS request.
173 * @return a map of the PNF data
175 private Map<String, String> convertPnfToAaiProperties() {
176 // convert PNF data to a Map
177 StandardCoderObject pnf = params.getContext().getProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()));
178 Map<String, Object> source = Util.translateToMap(getFullName(), pnf);
180 Map<String, String> result = new LinkedHashMap<>();
182 for (Entry<String, Object> ent : source.entrySet()) {
183 result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
190 * Converts the A&AI Custom Query data to a map suitable for passing via the
191 * "aaiProperties" field in the CDS request.
193 * @return a map of the custom query data
195 private Map<String, String> convertCqToAaiProperties() {
196 AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
198 Map<String, String> result = new LinkedHashMap<>();
200 ServiceInstance serviceInstance = aaicq.getServiceInstance();
201 if (serviceInstance == null) {
202 throw new IllegalArgumentException("Target service instance could not be found");
205 GenericVnf genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
206 if (genericVnf == null) {
207 throw new IllegalArgumentException("Target generic vnf could not be found");
210 result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId());
211 result.put(AAI_VNF_ID_KEY, genericVnf.getVnfId());
217 public void generateSubRequestId(int attempt) {
218 setSubRequestId("0");
225 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
228 * construct the request first so that we don't have to clean up the "client" if
229 * an exception is thrown
231 ExecutionServiceInput request = constructRequest(params);
233 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
235 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
236 config.getCdsServerProperties());
238 client.sendRequest(request);
240 // arrange to shutdown the client when the request completes
241 PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
243 controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
244 .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
250 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
251 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
252 * item for Frankfurt release.
254 * @param params the control loop parameters specifying the onset, payload, etc.
255 * @return an ExecutionServiceInput instance.
257 public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
259 // For the current operational TOSCA policy model (yaml) CBA name and version are
260 // embedded in the payload
261 // section, with the new policy type model being proposed in Frankfurt we will be
262 // able to move it out.
263 if (!validateCdsMandatoryParams(params)) {
264 throw new IllegalArgumentException("missing cds mandatory params - " + params);
266 Map<String, String> payload = convertPayloadMap(params.getPayload());
267 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
268 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
270 // Retain only the payload by removing CBA name and version once they are
272 // to be put in CDS request header.
273 payload.remove(CdsActorConstants.KEY_CBA_NAME);
274 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
276 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
277 // into grpc request.
278 String cbaActionName = params.getOperation();
279 CdsActionRequest request = new CdsActionRequest();
280 request.setPolicyPayload(payload);
281 request.setActionName(cbaActionName);
282 request.setResolutionKey(UUID.randomUUID().toString());
284 // Inject AAI properties into payload map. Offer flexibility to the usecase
285 // implementation to inject whatever AAI parameters are of interest to them.
286 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
289 // Note: that is a future enhancement. For now, the actor is hard-coded to
290 // use the A&AI query result specific to the target type
291 request.setAaiProperties(aaiConverter.get());
293 // Inject any additional event parameters that may be present in the onset event
294 if (params.getContext().getEvent().getAdditionalEventParams() != null) {
295 request.setAdditionalEventParams(params.getContext().getEvent().getAdditionalEventParams());
298 Builder struct = Struct.newBuilder();
300 String requestStr = request.generateCdsPayload();
301 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
302 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
303 JsonFormat.parser().merge(requestStr, struct);
304 } catch (InvalidProtocolBufferException | CoderException e) {
305 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
306 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
309 // Build CDS gRPC request common-header
310 CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
311 .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
313 // Build CDS gRPC request action-identifier
314 ActionIdentifiers actionIdentifiers =
315 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
316 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
318 // Finally build & return the ExecutionServiceInput gRPC request object.
319 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
320 .setPayload(struct.build()).build();
323 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
324 Map<String, String> convertedPayload = new HashMap<>();
325 for (Entry<String, Object> entry : payload.entrySet()) {
326 convertedPayload.put(entry.getKey(), entry.getValue().toString());
328 return convertedPayload;
331 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
332 if (params == null || params.getPayload() == null) {
335 Map<String, Object> payload = params.getPayload();
336 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
337 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
340 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
341 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
342 && !Strings.isNullOrEmpty(params.getOperation());