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.policy.TargetType;
57 * Operation that uses gRPC to send request to CDS.
61 public class GrpcOperation extends OperationPartial {
63 public static final String NAME = "any";
65 private static final String AAI_PNF_PREFIX = "pnf.";
66 private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
67 private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
69 private CdsProcessorGrpcClient client;
72 * Configuration for this operation.
74 private final GrpcConfig config;
77 * Function to request the A&AI data appropriate to the target type.
79 private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
82 * Function to convert the A&AI data associated with the target type.
84 private final Supplier<Map<String, String>> aaiConverter;
87 * Constructs the object.
89 * @param params operation parameters
90 * @param config configuration for this operation
92 public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
93 super(params, config);
96 if (TargetType.PNF.equals(params.getTarget().getType())) {
97 aaiRequestor = this::getPnf;
98 aaiConverter = this::convertPnfToAaiProperties;
100 aaiRequestor = this::getCq;
101 aaiConverter = this::convertCqToAaiProperties;
106 * If no timeout is specified, then it returns the operator's configured timeout.
109 protected long getTimeoutMs(Integer timeoutSec) {
110 return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
114 * Ensures that A&AI query has been performed, and runs the guard.
117 @SuppressWarnings("unchecked")
118 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
119 // run A&AI Query and Guard, in parallel
120 return allOf(aaiRequestor, this::startGuardAsync);
124 * Requests the A&AI PNF data.
126 * @return a future to get the PNF data
128 private CompletableFuture<OperationOutcome> getPnf() {
129 ControlLoopOperationParams pnfParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
130 .operation(AaiGetPnfOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
132 return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
136 * Requests the A&AI Custom Query data.
138 * @return a future to get the custom query data
140 private CompletableFuture<OperationOutcome> getCq() {
141 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
142 .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
144 return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
148 * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
149 * field in the CDS request.
151 * @return a map of the PNF data
153 private Map<String, String> convertPnfToAaiProperties() {
154 // convert PNF data to a Map
155 StandardCoderObject pnf = params.getContext().getProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()));
156 Map<String, Object> source = Util.translateToMap(getFullName(), pnf);
158 Map<String, String> result = new LinkedHashMap<>();
160 for (Entry<String, Object> ent : source.entrySet()) {
161 result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
168 * Converts the A&AI Custom Query data to a map suitable for passing via the
169 * "aaiProperties" field in the CDS request.
171 * @return a map of the custom query data
173 private Map<String, String> convertCqToAaiProperties() {
174 AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
176 Map<String, String> result = new LinkedHashMap<>();
178 ServiceInstance serviceInstance = aaicq.getServiceInstance();
179 if (serviceInstance == null) {
180 throw new IllegalArgumentException("Target service instance could not be found");
183 GenericVnf genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
184 if (genericVnf == null) {
185 throw new IllegalArgumentException("Target generic vnf could not be found");
188 result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId());
189 result.put(AAI_VNF_ID_KEY, genericVnf.getVnfId());
195 public void generateSubRequestId(int attempt) {
196 setSubRequestId("0");
203 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
205 CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
206 client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
207 config.getCdsServerProperties());
209 ExecutionServiceInput request = constructRequest(params);
210 client.sendRequest(request);
215 * Build the CDS ExecutionServiceInput request from the policy object and the AAI
216 * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
217 * item for Frankfurt release.
219 * @param params the control loop parameters specifying the onset, payload, etc.
220 * @return an ExecutionServiceInput instance.
222 public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
224 // For the current operational TOSCA policy model (yaml) CBA name and version are
225 // embedded in the payload
226 // section, with the new policy type model being proposed in Frankfurt we will be
227 // able to move it out.
228 if (!validateCdsMandatoryParams(params)) {
229 throw new IllegalArgumentException("missing cds mandatory params - " + params);
231 Map<String, String> payload = convertPayloadMap(params.getPayload());
232 String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
233 String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
235 // Retain only the payload by removing CBA name and version once they are
237 // to be put in CDS request header.
238 payload.remove(CdsActorConstants.KEY_CBA_NAME);
239 payload.remove(CdsActorConstants.KEY_CBA_VERSION);
241 // Embed payload from policy to ConfigDeployRequest object, serialize and inject
242 // into grpc request.
243 String cbaActionName = params.getOperation();
244 CdsActionRequest request = new CdsActionRequest();
245 request.setPolicyPayload(payload);
246 request.setActionName(cbaActionName);
247 request.setResolutionKey(UUID.randomUUID().toString());
249 // Inject AAI properties into payload map. Offer flexibility to the usecase
250 // implementation to inject whatever AAI parameters are of interest to them.
251 // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
254 // Note: that is a future enhancement. For now, the actor is hard-coded to
255 // use the A&AI query result specific to the target type
256 request.setAaiProperties(aaiConverter.get());
258 // Inject any additional event parameters that may be present in the onset event
259 if (params.getContext().getEvent().getAdditionalEventParams() != null) {
260 request.setAdditionalEventParams(params.getContext().getEvent().getAdditionalEventParams());
263 Builder struct = Struct.newBuilder();
265 String requestStr = request.generateCdsPayload();
266 Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
267 "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
268 JsonFormat.parser().merge(requestStr, struct);
269 } catch (InvalidProtocolBufferException | CoderException e) {
270 throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
271 + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
274 // Build CDS gRPC request common-header
275 CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
276 .setRequestId(params.getContext().getEvent().getRequestId().toString())
277 .setSubRequestId(getSubRequestId()).build();
279 // Build CDS gRPC request action-identifier
280 ActionIdentifiers actionIdentifiers =
281 ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
282 .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
284 // Finally build & return the ExecutionServiceInput gRPC request object.
285 return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
286 .setPayload(struct.build()).build();
289 private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
290 Map<String, String> convertedPayload = new HashMap<>();
291 for (Entry<String, Object> entry : payload.entrySet()) {
292 convertedPayload.put(entry.getKey(), entry.getValue().toString());
294 return convertedPayload;
297 private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
298 if (params == null || params.getPayload() == null) {
301 Map<String, Object> payload = params.getPayload();
302 if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
303 || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
306 return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
307 && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
308 && !Strings.isNullOrEmpty(params.getOperation());