Merge "Add PNF support to new CDS actor"
[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.policy.TargetType;
55
56 /**
57  * Operation that uses gRPC to send request to CDS.
58  *
59  */
60 @Getter
61 public class GrpcOperation extends OperationPartial {
62
63     public static final String NAME = "any";
64
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";
68
69     private CdsProcessorGrpcClient client;
70
71     /**
72      * Configuration for this operation.
73      */
74     private final GrpcConfig config;
75
76     /**
77      * Function to request the A&AI data appropriate to the target type.
78      */
79     private final Supplier<CompletableFuture<OperationOutcome>> aaiRequestor;
80
81     /**
82      * Function to convert the A&AI data associated with the target type.
83      */
84     private final Supplier<Map<String, String>> aaiConverter;
85
86     /**
87      * Constructs the object.
88      *
89      * @param params operation parameters
90      * @param config configuration for this operation
91      */
92     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
93         super(params, config);
94         this.config = config;
95
96         if (TargetType.PNF.equals(params.getTarget().getType())) {
97             aaiRequestor = this::getPnf;
98             aaiConverter = this::convertPnfToAaiProperties;
99         } else {
100             aaiRequestor = this::getCq;
101             aaiConverter = this::convertCqToAaiProperties;
102         }
103     }
104
105     /**
106      * If no timeout is specified, then it returns the operator's configured timeout.
107      */
108     @Override
109     protected long getTimeoutMs(Integer timeoutSec) {
110         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
111     }
112
113     /**
114      * Ensures that A&AI query has been performed, and runs the guard.
115      */
116     @Override
117     @SuppressWarnings("unchecked")
118     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
119         // run A&AI Query and Guard, in parallel
120         return allOf(aaiRequestor, this::startGuardAsync);
121     }
122
123     /**
124      * Requests the A&AI PNF data.
125      *
126      * @return a future to get the PNF data
127      */
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();
131
132         return params.getContext().obtain(AaiGetPnfOperation.getKey(params.getTargetEntity()), pnfParams);
133     }
134
135     /**
136      * Requests the A&AI Custom Query data.
137      *
138      * @return a future to get the custom query data
139      */
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();
143
144         return params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams);
145     }
146
147     /**
148      * Converts the A&AI PNF data to a map suitable for passing via the "aaiProperties"
149      * field in the CDS request.
150      *
151      * @return a map of the PNF data
152      */
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);
157
158         Map<String, String> result = new LinkedHashMap<>();
159
160         for (Entry<String, Object> ent : source.entrySet()) {
161             result.put(AAI_PNF_PREFIX + ent.getKey(), ent.getValue().toString());
162         }
163
164         return result;
165     }
166
167     /**
168      * Converts the A&AI Custom Query data to a map suitable for passing via the
169      * "aaiProperties" field in the CDS request.
170      *
171      * @return a map of the custom query data
172      */
173     private Map<String, String> convertCqToAaiProperties() {
174         AaiCqResponse aaicq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
175
176         Map<String, String> result = new LinkedHashMap<>();
177
178         ServiceInstance serviceInstance = aaicq.getServiceInstance();
179         if (serviceInstance == null) {
180             throw new IllegalArgumentException("Target service instance could not be found");
181         }
182
183         GenericVnf genericVnf = aaicq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
184         if (genericVnf == null) {
185             throw new IllegalArgumentException("Target generic vnf could not be found");
186         }
187
188         result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId());
189         result.put(AAI_VNF_ID_KEY, genericVnf.getVnfId());
190
191         return result;
192     }
193
194     @Override
195     public void generateSubRequestId(int attempt) {
196         setSubRequestId("0");
197     }
198
199     /**
200      * {@inheritDoc}.
201      */
202     @Override
203     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
204
205         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
206         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
207                         config.getCdsServerProperties());
208
209         ExecutionServiceInput request = constructRequest(params);
210         client.sendRequest(request);
211         return future;
212     }
213
214     /**
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.
218      *
219      * @param params the control loop parameters specifying the onset, payload, etc.
220      * @return an ExecutionServiceInput instance.
221      */
222     public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
223
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);
230         }
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);
234
235         // Retain only the payload by removing CBA name and version once they are
236         // extracted
237         // to be put in CDS request header.
238         payload.remove(CdsActorConstants.KEY_CBA_NAME);
239         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
240
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());
248
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
252         // needed by CDS.
253         //
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());
257
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());
261         }
262
263         Builder struct = Struct.newBuilder();
264         try {
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);
272         }
273
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();
278
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();
283
284         // Finally build & return the ExecutionServiceInput gRPC request object.
285         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
286                         .setPayload(struct.build()).build();
287     }
288
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());
293         }
294         return convertedPayload;
295     }
296
297     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
298         if (params == null || params.getPayload() == null) {
299             return false;
300         }
301         Map<String, Object> payload = params.getPayload();
302         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
303                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
304             return false;
305         }
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());
309     }
310 }