24178125461720d5ecaba5eebe716c83db4d47ef
[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 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.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;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.UUID;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.function.Supplier;
37 import lombok.Getter;
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;
59
60 /**
61  * Operation that uses gRPC to send request to CDS.
62  *
63  */
64 @Getter
65 public class GrpcOperation extends OperationPartial {
66
67     public static final String NAME = "any";
68
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";
72
73     private CdsProcessorGrpcClient client;
74
75     /**
76      * Configuration for this operation.
77      */
78     private final GrpcConfig config;
79
80     /**
81      * Function to request the A&AI data appropriate to the target type.
82      */
83     private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
84
85     /**
86      * Function to convert the A&AI data associated with the target type.
87      */
88     private final Supplier<Map<String, String>> aaiConverter;
89
90
91     // @formatter:off
92     private static final List<String> PNF_PROPERTY_NAMES = List.of(
93                             OperationProperties.AAI_PNF,
94                             OperationProperties.EVENT_ADDITIONAL_PARAMS);
95
96
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);
101     // @formatter:on
102
103     /**
104      * Constructs the object.
105      *
106      * @param params operation parameters
107      * @param config configuration for this operation
108      */
109     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
110         super(params, config, Collections.emptyList());
111         this.config = config;
112
113         if (TargetType.PNF.equals(params.getTarget().getType())) {
114             aaiRequestor = this::getPnf;
115             aaiConverter = this::convertPnfToAaiProperties;
116         } else {
117             aaiRequestor = this::getCq;
118             aaiConverter = this::convertCqToAaiProperties;
119         }
120     }
121
122     @Override
123     public List<String> getPropertyNames() {
124         return (TargetType.PNF.equals(params.getTarget().getType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
125     }
126
127     /**
128      * If no timeout is specified, then it returns the operator's configured timeout.
129      */
130     @Override
131     protected long getTimeoutMs(Integer timeoutSec) {
132         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
133     }
134
135     /**
136      * Ensures that A&AI query has been performed, and runs the guard.
137      */
138     @Override
139     @SuppressWarnings("unchecked")
140     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
141         // run A&AI Query and Guard, in parallel
142         return allOf(aaiRequestor, this::startGuardAsync);
143     }
144
145     /**
146      * Requests the A&AI PNF data.
147      *
148      * @return a future to get the PNF data
149      */
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();
153
154         return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
155     }
156
157     /**
158      * Requests the A&AI Custom Query data.
159      *
160      * @return a future to get the custom query data
161      */
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();
165
166         return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
167     }
168
169     /**
170      * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
171      * field in the CDS request.
172      *
173      * @return a map of the PNF data
174      */
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);
179
180         Map<String, String> result = new LinkedHashMap<>();
181
182         for (Entry<String, Object> ent : source.entrySet()) {
183             result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
184         }
185
186         return result;
187     }
188
189     /**
190      * Converts the A&AI Custom Query data to a map suitable for passing via the
191      * "aaiProperties" field in the CDS request.
192      *
193      * @return a map of the custom query data
194      */
195     private Map<String, String> convertCqToAaiProperties() {
196         AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
197
198         Map<String, String> result = new LinkedHashMap<>();
199
200         ServiceInstance serviceInstance = aaicq.getServiceInstance();
201         if (serviceInstance == null) {
202             throw new IllegalArgumentException("Target service instance could not be found");
203         }
204
205         GenericVnf genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
206         if (genericVnf == null) {
207             throw new IllegalArgumentException("Target generic vnf could not be found");
208         }
209
210         result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId());
211         result.put(AAI_VNF_ID_KEY, genericVnf.getVnfId());
212
213         return result;
214     }
215
216     @Override
217     public void generateSubRequestId(int attempt) {
218         setSubRequestId("0");
219     }
220
221     /**
222      * {@inheritDoc}.
223      */
224     @Override
225     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
226
227         /*
228          * construct the request first so that we don't have to clean up the "client" if
229          * an exception is thrown
230          */
231         ExecutionServiceInput request = constructRequest(params);
232
233         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
234
235         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
236                         config.getCdsServerProperties());
237
238         client.sendRequest(request);
239
240         // arrange to shutdown the client when the request completes
241         PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
242
243         controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
244                         .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
245
246         return controller;
247     }
248
249     /**
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.
253      *
254      * @param params the control loop parameters specifying the onset, payload, etc.
255      * @return an ExecutionServiceInput instance.
256      */
257     public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
258
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);
265         }
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);
269
270         // Retain only the payload by removing CBA name and version once they are
271         // extracted
272         // to be put in CDS request header.
273         payload.remove(CdsActorConstants.KEY_CBA_NAME);
274         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
275
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());
283
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
287         // needed by CDS.
288         //
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());
292
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());
296         }
297
298         Builder struct = Struct.newBuilder();
299         try {
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);
307         }
308
309         // Build CDS gRPC request common-header
310         CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
311                         .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
312
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();
317
318         // Finally build & return the ExecutionServiceInput gRPC request object.
319         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
320                         .setPayload(struct.build()).build();
321     }
322
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());
327         }
328         return convertedPayload;
329     }
330
331     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
332         if (params == null || params.getPayload() == null) {
333             return false;
334         }
335         Map<String, Object> payload = params.getPayload();
336         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
337                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
338             return false;
339         }
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());
343     }
344 }