2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controlloop.actor.so;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Optional;
28 import java.util.concurrent.CompletableFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Function;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.Response;
34 import org.onap.aai.domain.yang.CloudRegion;
35 import org.onap.aai.domain.yang.GenericVnf;
36 import org.onap.aai.domain.yang.ServiceInstance;
37 import org.onap.aai.domain.yang.Tenant;
38 import org.onap.policy.aai.AaiConstants;
39 import org.onap.policy.aai.AaiCqResponse;
40 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
42 import org.onap.policy.common.utils.coder.Coder;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
46 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
47 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
48 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
49 import org.onap.policy.controlloop.policy.PolicyResult;
50 import org.onap.policy.controlloop.policy.Target;
51 import org.onap.policy.so.SoCloudConfiguration;
52 import org.onap.policy.so.SoModelInfo;
53 import org.onap.policy.so.SoRequest;
54 import org.onap.policy.so.SoRequestInfo;
55 import org.onap.policy.so.SoRequestParameters;
56 import org.onap.policy.so.SoRequestStatus;
57 import org.onap.policy.so.SoResponse;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetGetCount()}
63 * each time they issue an HTTP request.
65 public abstract class SoOperation extends HttpOperation<SoResponse> {
66 private static final Logger logger = LoggerFactory.getLogger(SoOperation.class);
67 private static final Coder coder = new StandardCoder();
69 public static final String PAYLOAD_KEY_VF_COUNT = "vfCount";
70 public static final String FAILED = "FAILED";
71 public static final String COMPLETE = "COMPLETE";
72 public static final int SO_RESPONSE_CODE = 999;
74 // fields within the policy payload
75 public static final String REQ_PARAM_NM = "requestParameters";
76 public static final String CONFIG_PARAM_NM = "configurationParameters";
78 private final SoConfig config;
80 // values extracted from the parameter Target
81 private final String modelCustomizationId;
82 private final String modelInvariantId;
83 private final String modelVersionId;
85 private final String vfCountKey;
88 * Number of "get" requests issued so far, on the current operation attempt.
95 * Constructs the object.
97 * @param params operation parameters
98 * @param config configuration for this operation
100 public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
101 super(params, config, SoResponse.class);
102 this.config = (SoConfig) config;
104 verifyNotNull("Target information", params.getTarget());
106 this.modelCustomizationId = params.getTarget().getModelCustomizationId();
107 this.modelInvariantId = params.getTarget().getModelInvariantId();
108 this.modelVersionId = params.getTarget().getModelVersionId();
110 vfCountKey = SoConstants.VF_COUNT_PREFIX + "[" + modelCustomizationId + "][" + modelInvariantId + "]["
111 + modelVersionId + "]";
115 * Subclasses should invoke this before issuing their first HTTP request.
117 protected void resetGetCount() {
122 * Validates that the parameters contain the required target information to extract
123 * the VF count from the custom query.
125 protected void validateTarget() {
126 verifyNotNull("model-customization-id", modelCustomizationId);
127 verifyNotNull("model-invariant-id", modelInvariantId);
128 verifyNotNull("model-version-id", modelVersionId);
131 private void verifyNotNull(String type, Object value) {
133 throw new IllegalArgumentException("missing " + type + " for guard payload");
141 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
142 return startGuardAsync();
148 * @return a future to cancel or await the VF Count
150 @SuppressWarnings("unchecked")
151 protected CompletableFuture<OperationOutcome> obtainVfCount() {
152 if (params.getContext().contains(vfCountKey)) {
153 // already have the VF count
157 // need custom query from which to extract the VF count
158 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
159 .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
161 // run Custom Query and then extract the VF count
162 return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::storeVfCount);
166 * Stores the VF count.
168 * @return {@code null}
170 private CompletableFuture<OperationOutcome> storeVfCount() {
171 if (!params.getContext().contains(vfCountKey)) {
172 AaiCqResponse cq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
173 int vfcount = cq.getVfModuleCount(modelCustomizationId, modelInvariantId, modelVersionId);
175 params.getContext().setProperty(vfCountKey, vfcount);
181 protected int getVfCount() {
182 return params.getContext().getProperty(vfCountKey);
185 protected void setVfCount(int vfCount) {
186 params.getContext().setProperty(vfCountKey, vfCount);
190 * If the response does not indicate that the request has been completed, then sleep a
191 * bit and issue a "get".
194 protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
195 Response rawResponse, SoResponse response) {
197 // see if the request has "completed", whether or not it was successful
198 if (rawResponse.getStatus() == 200) {
199 String requestState = getRequestState(response);
200 if (COMPLETE.equalsIgnoreCase(requestState)) {
201 successfulCompletion();
202 return CompletableFuture
203 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
206 if (FAILED.equalsIgnoreCase(requestState)) {
207 return CompletableFuture
208 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
214 // need a request ID with which to query
215 if (response == null || response.getRequestReferences() == null
216 || response.getRequestReferences().getRequestId() == null) {
217 throw new IllegalArgumentException("missing request ID in response");
220 // see if the limit for the number of "gets" has been reached
221 if (getCount++ >= getMaxGets()) {
222 logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
223 setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
224 outcome.setMessage(SO_RESPONSE_CODE + " " + outcome.getMessage());
225 return CompletableFuture.completedFuture(outcome);
228 // sleep and then perform a "get" operation
229 Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
230 return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
234 * Invoked when a request completes successfully.
236 protected void successfulCompletion() {
241 * Issues a "get" request to see if the original request is complete yet.
243 * @param outcome outcome to be populated with the response
244 * @param response previous response
245 * @return a future that can be used to cancel the "get" request or await its response
247 private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, SoResponse response) {
248 String path = getPathGet() + response.getRequestReferences().getRequestId();
249 String url = getClient().getBaseUrl() + path;
251 logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
253 logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
255 // TODO should this use "path" or the full "url"?
256 return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
260 * Gets the request state of a response.
262 * @param response response from which to get the state
263 * @return the request state of the response, or {@code null} if it does not exist
265 protected String getRequestState(SoResponse response) {
266 SoRequest request = response.getRequest();
267 if (request == null) {
271 SoRequestStatus status = request.getRequestStatus();
272 if (status == null) {
276 return status.getRequestState();
280 * Treats everything as a success, so we always go into
281 * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
284 protected boolean isSuccess(Response rawResponse, SoResponse response) {
289 * Prepends the message with the http status code.
292 public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
293 SoResponse response) {
295 // set default result and message
296 setOutcome(outcome, result);
298 outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
302 protected SoModelInfo prepareSoModelInfo() {
303 Target target = params.getTarget();
304 if (target == null) {
305 throw new IllegalArgumentException("missing Target");
308 if (target.getModelCustomizationId() == null || target.getModelInvariantId() == null
309 || target.getModelName() == null || target.getModelVersion() == null
310 || target.getModelVersionId() == null) {
311 throw new IllegalArgumentException("missing VF Module model");
314 SoModelInfo soModelInfo = new SoModelInfo();
315 soModelInfo.setModelCustomizationId(target.getModelCustomizationId());
316 soModelInfo.setModelInvariantId(target.getModelInvariantId());
317 soModelInfo.setModelName(target.getModelName());
318 soModelInfo.setModelVersion(target.getModelVersion());
319 soModelInfo.setModelVersionId(target.getModelVersionId());
320 soModelInfo.setModelType("vfModule");
325 * Construct requestInfo for the SO requestDetails.
327 * @return SO request information
329 protected SoRequestInfo constructRequestInfo() {
330 SoRequestInfo soRequestInfo = new SoRequestInfo();
331 soRequestInfo.setSource("POLICY");
332 soRequestInfo.setSuppressRollback(false);
333 soRequestInfo.setRequestorId("policy");
334 return soRequestInfo;
338 * Builds the request parameters from the policy payload.
340 protected Optional<SoRequestParameters> buildRequestParameters() {
341 if (params.getPayload() == null) {
342 return Optional.empty();
345 Object data = params.getPayload().get(REQ_PARAM_NM);
347 return Optional.empty();
351 return Optional.of(coder.decode(data.toString(), SoRequestParameters.class));
352 } catch (CoderException e) {
353 throw new IllegalArgumentException("invalid payload value: " + REQ_PARAM_NM);
358 * Builds the configuration parameters from the policy payload.
360 protected Optional<List<Map<String, String>>> buildConfigurationParameters() {
361 if (params.getPayload() == null) {
362 return Optional.empty();
365 Object data = params.getPayload().get(CONFIG_PARAM_NM);
367 return Optional.empty();
371 @SuppressWarnings("unchecked")
372 List<Map<String, String>> result = coder.decode(data.toString(), ArrayList.class);
373 return Optional.of(result);
374 } catch (CoderException | RuntimeException e) {
375 throw new IllegalArgumentException("invalid payload value: " + CONFIG_PARAM_NM);
380 * Construct cloudConfiguration for the SO requestDetails. Overridden for custom
383 * @param tenantItem tenant item from A&AI named-query response
384 * @return SO cloud configuration
386 protected SoCloudConfiguration constructCloudConfigurationCq(Tenant tenantItem, CloudRegion cloudRegionItem) {
387 SoCloudConfiguration cloudConfiguration = new SoCloudConfiguration();
388 cloudConfiguration.setTenantId(tenantItem.getTenantId());
389 cloudConfiguration.setLcpCloudRegionId(cloudRegionItem.getCloudRegionId());
390 return cloudConfiguration;
394 * Create simple HTTP headers for unauthenticated requests to SO.
396 * @return the HTTP headers
398 protected Map<String, Object> createSimpleHeaders() {
399 Map<String, Object> headers = new HashMap<>();
400 headers.put("Accept", MediaType.APPLICATION_JSON);
405 * These methods extract data from the Custom Query and throw an
406 * IllegalArgumentException if the desired data item is not found.
409 protected GenericVnf getVnfItem(AaiCqResponse aaiCqResponse, SoModelInfo soModelInfo) {
410 GenericVnf vnf = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
412 throw new IllegalArgumentException("missing generic VNF");
418 protected ServiceInstance getServiceInstance(AaiCqResponse aaiCqResponse) {
419 ServiceInstance vnfService = aaiCqResponse.getServiceInstance();
420 if (vnfService == null) {
421 throw new IllegalArgumentException("missing VNF Service Item");
427 protected Tenant getDefaultTenant(AaiCqResponse aaiCqResponse) {
428 Tenant tenant = aaiCqResponse.getDefaultTenant();
429 if (tenant == null) {
430 throw new IllegalArgumentException("missing Tenant Item");
436 protected CloudRegion getDefaultCloudRegion(AaiCqResponse aaiCqResponse) {
437 CloudRegion cloudRegion = aaiCqResponse.getDefaultCloudRegion();
438 if (cloudRegion == null) {
439 throw new IllegalArgumentException("missing Cloud Region");
445 // these may be overridden by junit tests
448 * Gets the wait time, in milliseconds, between "get" requests.
450 * @return the wait time, in milliseconds, between "get" requests
452 public long getWaitMsGet() {
453 return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
456 public int getMaxGets() {
457 return config.getMaxGets();
460 public String getPathGet() {
461 return config.getPathGet();
464 public int getWaitSecGet() {
465 return config.getWaitSecGet();