Set sub request ID before start callback
[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  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.controlloop.actor.cds;
20
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Strings;
23 import com.google.protobuf.InvalidProtocolBufferException;
24 import com.google.protobuf.Struct;
25 import com.google.protobuf.Struct.Builder;
26 import com.google.protobuf.util.JsonFormat;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.UUID;
31 import java.util.concurrent.CompletableFuture;
32 import lombok.Getter;
33 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
34 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
35 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
36 import org.onap.policy.aai.AaiConstants;
37 import org.onap.policy.aai.AaiCqResponse;
38 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.controlloop.actor.aai.AaiCustomQueryOperation;
41 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
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.impl.OperationPartial;
45 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
46
47 /**
48  * Operation that uses gRPC to send request to CDS.
49  *
50  */
51 @Getter
52 public class GrpcOperation extends OperationPartial {
53
54     public static final String NAME = "gRPC";
55
56     private CdsProcessorGrpcClient client;
57
58     /**
59      * Configuration for this operation.
60      */
61     private final GrpcConfig config;
62
63     /**
64      * Constructs the object.
65      *
66      * @param params operation parameters
67      * @param config configuration for this operation
68      */
69     public GrpcOperation(ControlLoopOperationParams params, GrpcConfig config) {
70         super(params, config);
71         this.config = config;
72     }
73
74     /**
75      * If no timeout is specified, then it returns the operator's configured timeout.
76      */
77     @Override
78     protected long getTimeoutMs(Integer timeoutSec) {
79         return (timeoutSec == null || timeoutSec == 0 ? config.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
80     }
81
82     /**
83      * Ensures that A&AI customer query has been performed.
84      */
85     @Override
86     @SuppressWarnings("unchecked")
87     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
88         ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
89                         .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build();
90
91         // run Custom Query and Guard, in parallel
92         return allOf(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::startGuardAsync);
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         CompletableFuture<OperationOutcome> future = new CompletableFuture<>();
107         client = new CdsProcessorGrpcClient(new CdsActorServiceManager(outcome, future),
108                         config.getCdsServerProperties());
109
110         ExecutionServiceInput request = constructRequest(params);
111         client.sendRequest(request);
112         return future;
113     }
114
115     /**
116      * Build the CDS ExecutionServiceInput request from the policy object and the AAI
117      * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD
118      * item for Frankfurt release.
119      *
120      * @param params the control loop parameters specifying the onset, payload, etc.
121      * @return an ExecutionServiceInput instance.
122      */
123     public ExecutionServiceInput constructRequest(ControlLoopOperationParams params) {
124
125         // For the current operational TOSCA policy model (yaml) CBA name and version are
126         // embedded in the payload
127         // section, with the new policy type model being proposed in Frankfurt we will be
128         // able to move it out.
129         if (!validateCdsMandatoryParams(params)) {
130             throw new IllegalArgumentException("missing cds mandatory params -  " + params);
131         }
132         Map<String, String> payload = convertPayloadMap(params.getPayload());
133         String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME);
134         String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION);
135
136         // Retain only the payload by removing CBA name and version once they are
137         // extracted
138         // to be put in CDS request header.
139         payload.remove(CdsActorConstants.KEY_CBA_NAME);
140         payload.remove(CdsActorConstants.KEY_CBA_VERSION);
141
142         // Embed payload from policy to ConfigDeployRequest object, serialize and inject
143         // into grpc request.
144         String cbaActionName = params.getOperation();
145         CdsActionRequest request = new CdsActionRequest();
146         request.setPolicyPayload(payload);
147         request.setActionName(cbaActionName);
148         request.setResolutionKey(UUID.randomUUID().toString());
149
150         // Inject AAI properties into payload map. Offer flexibility to the usecase
151         // implementation to inject whatever AAI parameters are of interest to them.
152         // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as
153         // needed by CDS.
154         request.setAaiProperties(params.getContext().getEnrichment());
155
156         // Inject any additional event parameters that may be present in the onset event
157         if (params.getContext().getEvent().getAdditionalEventParams() != null) {
158             request.setAdditionalEventParams(params.getContext().getEvent().getAdditionalEventParams());
159         }
160
161         Builder struct = Struct.newBuilder();
162         try {
163             String requestStr = request.generateCdsPayload();
164             Preconditions.checkState(!Strings.isNullOrEmpty(requestStr),
165                             "Unable to build " + "config-deploy-request from payload parameters: {}", payload);
166             JsonFormat.parser().merge(requestStr, struct);
167         } catch (InvalidProtocolBufferException | CoderException e) {
168             throw new IllegalArgumentException("Failed to embed CDS payload string into the input request. blueprint({"
169                             + cbaName + "}:{" + cbaVersion + "}) for action({" + cbaActionName + "})", e);
170         }
171
172         // Build CDS gRPC request common-header
173         CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID)
174                         .setRequestId(params.getContext().getEvent().getRequestId().toString())
175                         .setSubRequestId(getSubRequestId()).build();
176
177         // Build CDS gRPC request action-identifier
178         ActionIdentifiers actionIdentifiers =
179                         ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion)
180                                         .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build();
181
182         // Finally build & return the ExecutionServiceInput gRPC request object.
183         return ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers)
184                         .setPayload(struct.build()).build();
185     }
186
187     private Map<String, String> convertPayloadMap(Map<String, Object> payload) {
188         Map<String, String> convertedPayload = new HashMap<>();
189         for (Entry<String, Object> entry : payload.entrySet()) {
190             convertedPayload.put(entry.getKey(), entry.getValue().toString());
191         }
192         return convertedPayload;
193     }
194
195     private boolean validateCdsMandatoryParams(ControlLoopOperationParams params) {
196         if (params == null || params.getPayload() == null) {
197             return false;
198         }
199         Map<String, Object> payload = params.getPayload();
200         if (payload.get(CdsActorConstants.KEY_CBA_NAME) == null
201                         || payload.get(CdsActorConstants.KEY_CBA_VERSION) == null) {
202             return false;
203         }
204         return !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_NAME).toString())
205                         && !Strings.isNullOrEmpty(payload.get(CdsActorConstants.KEY_CBA_VERSION).toString())
206                         && !Strings.isNullOrEmpty(params.getOperation());
207     }
208 }