Modify Actors to use properties when provided
[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.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.Util;
54 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
55 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
56 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
57 import org.onap.policy.controlloop.policy.TargetType;
58
59 /**
60  * Operation that uses gRPC to send request to CDS.
61  *
62  */
63 @Getter
64 public class GrpcOperation extends OperationPartial {
65
66     public static final String NAME = "any";
67
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";
71
72     private CdsProcessorGrpcClient client;
73
74     /**
75      * Configuration for this operation.
76      */
77     private final GrpcConfig config;
78
79     /**
80      * Function to request the A&AI data appropriate to the target type.
81      */
82     private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
83
84     /**
85      * Function to convert the A&AI data associated with the target type.
86      */
87     private final Supplier<Map<String, String>> aaiConverter;
88
89
90     // @formatter:off
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);
95
96
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);
102     // @formatter:on
103
104     /**
105      * Constructs the object.
106      *
107      * @param params operation parameters
108      * @param config configuration for this operation
109      */
110     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
111         super(params, config, Collections.emptyList());
112         this.config = config;
113
114         if (TargetType.PNF.equals(params.getTarget().getType())) {
115             aaiRequestor = this::getPnf;
116             aaiConverter = this::convertPnfToAaiProperties;
117         } else {
118             aaiRequestor = this::getCq;
119             aaiConverter = this::convertCqToAaiProperties;
120         }
121     }
122
123     @Override
124     public List<String> getPropertyNames() {
125         return (TargetType.PNF.equals(params.getTarget().getType()) ? PNF_PROPERTY_NAMES : VNF_PROPERTY_NAMES);
126     }
127
128     /**
129      * If no timeout is specified, then it returns the operator's configured timeout.
130      */
131     @Override
132     protected long getTimeoutMs(Integer timeoutSec) {
133         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
134     }
135
136     /**
137      * Ensures that A&AI query has been performed, and runs the guard.
138      */
139     @Override
140     @SuppressWarnings("unchecked")
141     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
142         if (params.isPreprocessed()) {
143             return null;
144         }
145
146         // run A&AI Query and Guard, in parallel
147         return allOf(aaiRequestor, this::startGuardAsync);
148     }
149
150     /**
151      * Requests the A&AI PNF data.
152      *
153      * @return a future to get the PNF data
154      */
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();
158
159         return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
160     }
161
162     /**
163      * Requests the A&AI Custom Query data.
164      *
165      * @return a future to get the custom query data
166      */
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();
170
171         return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
172     }
173
174     /**
175      * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
176      * field in the CDS request.
177      *
178      * @return a map of the PNF data
179      */
180     private Map<String, String> convertPnfToAaiProperties() {
181         Map<String, String> result = this.getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
182         if (result != null) {
183             return result;
184         }
185
186         // convert PNF data to a Map
187         Map<String, Object> source = Util.translateToMap(getFullName(), getPnfData());
188
189         result = new LinkedHashMap<>();
190
191         for (Entry<String, Object> ent : source.entrySet()) {
192             result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
193         }
194
195         return result;
196     }
197
198     /**
199      * Gets the PNF from the operation properties, if it exists, or from the context
200      * properties otherwise.
201      *
202      * @return the PNF item
203      */
204     protected Object getPnfData() {
205         Object pnf = getProperty(OperationProperties.AAI_PNF);
206         if (pnf != null) {
207             return pnf;
208         }
209
210         pnf = params.getContext().getProperty(AaiGetPnfOperation.getKey(params.getTargetEntity()));
211         if (pnf == null) {
212             throw new IllegalArgumentException("missing PNF data");
213         }
214
215         return pnf;
216     }
217
218     /**
219      * Converts the A&AI Custom Query data to a map suitable for passing via the
220      * "aaiProperties" field in the CDS request.
221      *
222      * @return a map of the custom query data
223      */
224     private Map<String, String> convertCqToAaiProperties() {
225         Map<String, String> result = this.getProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES);
226         if (result != null) {
227             return result;
228         }
229
230         result = new LinkedHashMap<>();
231
232         result.put(AAI_SERVICE_INSTANCE_ID_KEY, getServiceInstanceId());
233         result.put(AAI_VNF_ID_KEY, getVnfId());
234
235         return result;
236     }
237
238     protected String getServiceInstanceId() {
239         ServiceInstance serviceInstance = getProperty(OperationProperties.AAI_SERVICE);
240         if (serviceInstance != null) {
241             return serviceInstance.getServiceInstanceId();
242         }
243
244         AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
245
246         serviceInstance = aaicq.getServiceInstance();
247         if (serviceInstance == null) {
248             throw new IllegalArgumentException("Target service instance could not be found");
249         }
250
251         return serviceInstance.getServiceInstanceId();
252     }
253
254     protected String getVnfId() {
255         GenericVnf genericVnf = getProperty(OperationProperties.AAI_RESOURCE_VNF);
256         if (genericVnf != null) {
257             return genericVnf.getVnfId();
258         }
259
260         AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
261
262         genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
263         if (genericVnf == null) {
264             throw new IllegalArgumentException("Target generic vnf could not be found");
265         }
266
267         return genericVnf.getVnfId();
268     }
269
270     @Override
271     public void generateSubRequestId(int attempt) {
272         setSubRequestId("0");
273     }
274
275     /**
276      * {@inheritDoc}.
277      */
278     @Override
279     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
280
281         /*
282          * construct the request first so that we don't have to clean up the "client" if
283          * an exception is thrown
284          */
285         ExecutionServiceInput request = constructRequest();
286
287         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
288
289         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
290                         config.getCdsServerProperties());
291
292         client.sendRequest(request);
293
294         // arrange to shutdown the client when the request completes
295         PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
296
297         controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
298                         .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
299
300         return controller;
301     }
302
303     /**
304      * Build the CDS ExecutionServiceInput request from the policy object and the AAI
305      * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
306      * item for Frankfurt release.
307      *
308      * @return an ExecutionServiceInput instance.
309      */
310     public ExecutionServiceInput constructRequest() {
311
312         // For the current operational TOSCA policy model (yaml) CBA name and version are
313         // embedded in the payload
314         // section, with the new policy type model being proposed in Frankfurt we will be
315         // able to move it out.
316         if (!validateCdsMandatoryParams(params)) {
317             throw new IllegalArgumentException("missing cds mandatory params -  " + params);
318         }
319         Map<String, String> payload = convertPayloadMap(params.getPayload());
320         String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
321         String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
322
323         // Retain only the payload by removing CBA name and version once they are
324         // extracted
325         // to be put in CDS request header.
326         payload.remove(CdsActorConstants.KEY_CBA_NAME);
327         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
328
329         // Embed payload from policy to ConfigDeployRequest object, serialize and inject
330         // into grpc request.
331         String cbaActionName = params.getOperation();
332         CdsActionRequest request = new CdsActionRequest();
333         request.setPolicyPayload(payload);
334         request.setActionName(cbaActionName);
335         request.setResolutionKey(UUID.randomUUID().toString());
336
337         // Inject AAI properties into payload map. Offer flexibility to the usecase
338         // implementation to inject whatever AAI parameters are of interest to them.
339         // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
340         // needed by CDS.
341         //
342         // Note: that is a future enhancement. For now, the actor is hard-coded to
343         // use the A&AI query result specific to the target type
344         request.setAaiProperties(aaiConverter.get());
345
346         // Inject any additional event parameters that may be present in the onset event
347         Map<String, String> additionalParams = getAdditionalEventParams();
348         if (additionalParams != null) {
349             request.setAdditionalEventParams(additionalParams);
350         }
351
352         Builder struct = Struct.newBuilder();
353         try {
354             String requestStr = request.generateCdsPayload();
355             Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
356                             "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
357             JsonFormat.parser().merge(requestStr, struct);
358         } catch (InvalidProtocolBufferException | CoderException e) {
359             throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
360                             + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
361         }
362
363         // Build CDS gRPC request common-header
364         CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
365                         .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
366
367         // Build CDS gRPC request action-identifier
368         ActionIdentifiers actionIdentifiers =
369                         ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
370                                         .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
371
372         // Finally build & return the ExecutionServiceInput gRPC request object.
373         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
374                         .setPayload(struct.build()).build();
375     }
376
377     protected Map<String, String> getAdditionalEventParams() {
378         if (containsProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS)) {
379             return getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
380         }
381
382         return params.getContext().getEvent().getAdditionalEventParams();
383     }
384
385     private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
386         Map<String, String> convertedPayload = new HashMap<>();
387         for (Entry<String, Object> entry : payload.entrySet()) {
388             convertedPayload.put(entry.getKey(), entry.getValue().toString());
389         }
390         return convertedPayload;
391     }
392
393     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
394         if (params == null || params.getPayload() == null) {
395             return false;
396         }
397         Map<String, Object> payload = params.getPayload();
398         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
399                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
400             return false;
401         }
402         return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
403                         && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
404                         && !Strings.isNullOrEmpty(params.getOperation());
405     }
406 }