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