extend vnf properties model for cds actors
[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-2022 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.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.UUID;
33 import java.util.concurrent.CompletableFuture;
34 import lombok.Getter;
35 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
36 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
37 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
38 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
41 import org.onap.policy.controlloop.actor.cds.properties.GrpcOperationProperties;
42 import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest;
43 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
44 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
45 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
46 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
47 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
48
49 /**
50  * Operation that uses gRPC to send request to CDS.
51  *
52  */
53 @Getter
54 public class GrpcOperation extends OperationPartial {
55
56     public static final String NAME = "any";
57
58     private CdsProcessorGrpcClient client;
59
60     /**
61      * Configuration for this operation.
62      */
63     private final GrpcConfig config;
64
65     /**
66      * Operation properties.
67      */
68     private final GrpcOperationProperties opProperties;
69
70     /**
71      * Constructs the object.
72      *
73      * @param params operation parameters
74      * @param config configuration for this operation
75      */
76     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
77         super(params, config, Collections.emptyList());
78         this.config = config;
79         this.opProperties = GrpcOperationProperties.build(params);
80     }
81
82     @Override
83     public List<String> getPropertyNames() {
84         return this.opProperties.getPropertyNames();
85     }
86
87     /**
88      * If no timeout is specified, then it returns the operator's configured timeout.
89      */
90     @Override
91     protected long getTimeoutMs(Integer timeoutSec) {
92         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
93     }
94
95     @Override
96     public void generateSubRequestId(int attempt) {
97         setSubRequestId("0");
98     }
99
100     /**
101      * {@inheritDoc}.
102      */
103     @Override
104     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
105
106         /*
107          * construct the request first so that we don't have to clean up the "client" if
108          * an exception is thrown
109          */
110         ExecutionServiceInput request = constructRequest();
111
112         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
113
114         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
115                         config.getCdsServerProperties());
116
117         client.sendRequest(request);
118
119         // arrange to shutdown the client when the request completes
120         PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
121
122         controller.wrap(future).whenCompleteAsync(controller.delayedComplete(), params.getExecutor())
123                         .whenCompleteAsync((arg1, arg2) -> client.close(), getBlockingExecutor());
124
125         return controller;
126     }
127
128     /**
129      * Build the CDS ExecutionServiceInput request from the policy object and the AAI
130      * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
131      * item for Frankfurt release.
132      *
133      * @return an ExecutionServiceInput instance.
134      */
135     public ExecutionServiceInput constructRequest() {
136
137         // For the current operational TOSCA policy model (yaml) CBA name and version are
138         // embedded in the payload
139         // section, with the new policy type model being proposed in Frankfurt we will be
140         // able to move it out.
141         if (!validateCdsMandatoryParams(params)) {
142             throw new IllegalArgumentException("missing cds mandatory params -  " + params);
143         }
144         Map<String, String> payload = convertPayloadMap(params.getPayload());
145         String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
146         String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
147
148         // Retain only the payload by removing CBA name and version once they are
149         // extracted
150         // to be put in CDS request header.
151         payload.remove(CdsActorConstants.KEY_CBA_NAME);
152         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
153
154         // Embed payload from policy to ConfigDeployRequest object, serialize and inject
155         // into grpc request.
156         String cbaActionName = params.getOperation();
157         var request = new CdsActionRequest();
158         request.setPolicyPayload(payload);
159         request.setActionName(cbaActionName);
160         request.setResolutionKey(UUID.randomUUID().toString());
161
162         // Inject AAI properties into payload map. Offer flexibility to the usecase
163         // implementation to inject whatever AAI parameters are of interest to them.
164         // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
165         // needed by CDS.
166         //
167         // Note: that is a future enhancement. For now, the actor is hard-coded to
168         // use the A&AI query result specific to the target type
169         request.setAaiProperties(opProperties.convertToAaiProperties(this));
170
171         // Inject any additional event parameters that may be present in the onset event
172         Map<String, String> additionalParams = getProperty(OperationProperties.EVENT_ADDITIONAL_PARAMS);
173         if (additionalParams != null) {
174             request.setAdditionalEventParams(additionalParams);
175         }
176
177         var struct = Struct.newBuilder();
178         try {
179             String requestStr = request.generateCdsPayload();
180             Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
181                             "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
182             JsonFormat.parser().merge(requestStr, struct);
183         } catch (InvalidProtocolBufferException | CoderException e) {
184             throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
185                             + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
186         }
187
188         // Build CDS gRPC request common-header
189         var commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
190                         .setRequestId(params.getRequestId().toString()).setSubRequestId(getSubRequestId()).build();
191
192         // Build CDS gRPC request action-identifier
193         var actionIdentifiers =
194                         ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
195                                         .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
196
197         // Finally build & return the ExecutionServiceInput gRPC request object.
198         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
199                         .setPayload(struct.build()).build();
200     }
201
202     private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
203         Map<String, String> convertedPayload = new HashMap<>();
204         for (Entry<String, Object> entry : payload.entrySet()) {
205             convertedPayload.put(entry.getKey(), entry.getValue().toString());
206         }
207         return convertedPayload;
208     }
209
210     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
211         if (params == null || params.getPayload() == null) {
212             return false;
213         }
214         Map<String, Object> payload = params.getPayload();
215         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
216                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
217             return false;
218         }
219         return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
220                         && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
221                         && !Strings.isNullOrEmpty(params.getOperation());
222     }
223 }