87eaa9572fa914558efbe6979dd48993361866f3
[policy/models.git] / models-interactions / model-actors / actor.cds / src / main / java / org / onap / policy / controlloop / actor / cds / GrpcOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020 Bell Canada. All rights reserved.
4  * Modifications Copyright (C) 2020-2021 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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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=========================================================
18  */
19
20 package org.onap.policy.controlloop.actor.cds;
21
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.util.JsonFormat;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.UUID;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.function.Supplier;
36 import lombok.Getter;
37 import org.onap.aai.domain.yang.GenericVnf;
38 import org.onap.aai.domain.yang.ServiceInstance;
39 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
40 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
41 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
42 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
45 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
46 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
47 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
48 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
49 import org.onap.policy.controlloop.actorserviceprovider.Util;
50 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
51 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
52 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
53
54 /**
55  * Operation that uses gRPC to send request to CDS.
56  *
57  */
58 @Getter
59 public class GrpcOperation extends OperationPartial {
60
61     public static final String NAME = "any";
62
63     private static final String AAI_PNF_PREFIX = "pnf.";
64     private static final String AAI_VNF_ID_KEY = "generic-vnf.vnf-id";
65     private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id";
66
67     private CdsProcessorGrpcClient client;
68
69     /**
70      * Configuration for this operation.
71      */
72     private final GrpcConfig config;
73
74     /**
75      * Function to convert the A&AI data associated with the target type.
76      */
77     private final Supplier<Map<String, String>> aaiConverter;
78
79
80     // @formatter:off
81     private static final List<String> PNF_PROPERTY_NAMES = List.of(
82                             OperationProperties.AAI_PNF,
83                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
84                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
85
86
87     private static final List<String> VNF_PROPERTY_NAMES = List.of(
88                             OperationProperties.AAI_RESOURCE_VNF,
89                             OperationProperties.AAI_SERVICE,
90                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
91                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
92     // @formatter:on
93
94     /**
95      * Constructs the object.
96      *
97      * @param params operation parameters
98      * @param config configuration for this operation
99      */
100     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
101         super(params, config, Collections.emptyList());
102         this.config = config;
103
104         if (TargetType.PNF.equals(params.getTargetType())) {
105             aaiConverter = this::convertPnfToAaiProperties;
106         } else {
107             aaiConverter = this::convertVnfToAaiProperties;
108         }
109     }
110
111     @Override
112     public List<String> getPropertyNames() {
113         return (TargetType.PNF.equals(params.getTargetType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
114     }
115
116     /**
117      * If no timeout is specified, then it returns the operator's configured timeout.
118      */
119     @Override
120     protected long getTimeoutMs(Integer timeoutSec) {
121         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
122     }
123
124     /**
125      * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
126      * field in the CDS request.
127      *
128      * @return a map of the PNF data
129      */
130     private Map<String, String> convertPnfToAaiProperties() {
131         Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
132         if (result != null) {
133             return result;
134         }
135
136         // convert PNF data to a Map
137         Object pnfData = getRequiredProperty(OperationProperties.AAI_PNF, "PNF");
138         Map<String, Object> source = Util.translateToMap(getFullName(), pnfData);
139
140         result = new LinkedHashMap<>();
141
142         for (Entry<String, Object> ent : source.entrySet()) {
143             result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
144         }
145
146         return result;
147     }
148
149     /**
150      * Converts the A&AI VNF data to a map suitable for passing via the
151      * "aaiProperties" field in the CDS request.
152      *
153      * @return a map of the VNF data
154      */
155     private Map<String, String> convertVnfToAaiProperties() {
156         Map<String, String> result = getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
157         if (result != null) {
158             return result;
159         }
160
161         result = new LinkedHashMap<>();
162
163         result.put(AAI_SERVICE_INSTANCE_ID_KEY, getServiceInstanceId());
164         result.put(AAI_VNF_ID_KEY, getVnfId());
165
166         return result;
167     }
168
169     protected String getServiceInstanceId() {
170         var serviceInstance = (ServiceInstance) getRequiredProperty(OperationProperties.AAI_SERVICE,
171                         "Target service instance");
172         return serviceInstance.getServiceInstanceId();
173     }
174
175     protected String getVnfId() {
176         var genericVnf = (GenericVnf) getRequiredProperty(OperationProperties.AAI_RESOURCE_VNF, "Target generic vnf");
177         return genericVnf.getVnfId();
178     }
179
180     @Override
181     public void generateSubRequestId(int attempt) {
182         setSubRequestId("0");
183     }
184
185     /**
186      * {@inheritDoc}.
187      */
188     @Override
189     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
190
191         /*
192          * construct the request first so that we don't have to clean up the "client" if
193          * an exception is thrown
194          */
195         ExecutionServiceInput request = constructRequest();
196
197         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
198
199         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
200                         config.getCdsServerProperties());
201
202         client.sendRequest(request);
203
204         // arrange to shutdown the client when the request completes
205         PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
206
207         controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
208                         .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
209
210         return controller;
211     }
212
213     /**
214      * Build the CDS ExecutionServiceInput request from the policy object and the AAI
215      * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
216      * item for Frankfurt release.
217      *
218      * @return an ExecutionServiceInput instance.
219      */
220     public ExecutionServiceInput constructRequest() {
221
222         // For the current operational TOSCA policy model (yaml) CBA name and version are
223         // embedded in the payload
224         // section, with the new policy type model being proposed in Frankfurt we will be
225         // able to move it out.
226         if (!validateCdsMandatoryParams(params)) {
227             throw new IllegalArgumentException("missing cds mandatory params -  " + params);
228         }
229         Map<String, String> payload = convertPayloadMap(params.getPayload());
230         String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
231         String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
232
233         // Retain only the payload by removing CBA name and version once they are
234         // extracted
235         // to be put in CDS request header.
236         payload.remove(CdsActorConstants.KEY_CBA_NAME);
237         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
238
239         // Embed payload from policy to ConfigDeployRequest object, serialize and inject
240         // into grpc request.
241         String cbaActionName = params.getOperation();
242         var request = new CdsActionRequest();
243         request.setPolicyPayload(payload);
244         request.setActionName(cbaActionName);
245         request.setResolutionKey(UUID.randomUUID().toString());
246
247         // Inject AAI properties into payload map. Offer flexibility to the usecase
248         // implementation to inject whatever AAI parameters are of interest to them.
249         // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
250         // needed by CDS.
251         //
252         // Note: that is a future enhancement. For now, the actor is hard-coded to
253         // use the A&AI query result specific to the target type
254         request.setAaiProperties(aaiConverter.get());
255
256         // Inject any additional event parameters that may be present in the onset event
257         Map<String, String> additionalParams = getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
258         if (additionalParams != null) {
259             request.setAdditionalEventParams(additionalParams);
260         }
261
262         var struct = Struct.newBuilder();
263         try {
264             String requestStr = request.generateCdsPayload();
265             Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
266                             "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
267             JsonFormat.parser().merge(requestStr, struct);
268         } catch (InvalidProtocolBufferException | CoderException e) {
269             throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
270                             + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
271         }
272
273         // Build CDS gRPC request common-header
274         var commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
275                         .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
276
277         // Build CDS gRPC request action-identifier
278         var actionIdentifiers =
279                         ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
280                                         .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
281
282         // Finally build & return the ExecutionServiceInput gRPC request object.
283         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
284                         .setPayload(struct.build()).build();
285     }
286
287     private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
288         Map<String, String> convertedPayload = new HashMap<>();
289         for (Entry<String, Object> entry : payload.entrySet()) {
290             convertedPayload.put(entry.getKey(), entry.getValue().toString());
291         }
292         return convertedPayload;
293     }
294
295     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
296         if (params == null || params.getPayload() == null) {
297             return false;
298         }
299         Map<String, Object> payload = params.getPayload();
300         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
301                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
302             return false;
303         }
304         return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
305                         && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
306                         && !Strings.isNullOrEmpty(params.getOperation());
307     }
308 }