2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2020 Wipro Limited.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.controlloop.actor.so;
25 import java.net.http.HttpRequest;
26 import java.net.http.HttpRequest.BodyPublishers;
27 import java.net.http.HttpRequest.Builder;
28 import java.net.http.HttpResponse;
29 import java.net.http.HttpResponse.BodyHandlers;
30 import java.nio.charset.StandardCharsets;
31 import java.util.Base64;
32 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.concurrent.CompletableFuture;
36 import javax.ws.rs.client.InvocationCallback;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.Response;
39 import org.apache.commons.lang3.StringUtils;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.onap.aai.domain.yang.CloudRegion;
42 import org.onap.aai.domain.yang.GenericVnf;
43 import org.onap.aai.domain.yang.ServiceInstance;
44 import org.onap.aai.domain.yang.Tenant;
45 import org.onap.policy.aai.AaiConstants;
46 import org.onap.policy.aai.AaiCqResponse;
47 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
48 import org.onap.policy.common.endpoints.http.client.HttpClient;
49 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
50 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
51 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
52 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
53 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
54 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
55 import org.onap.policy.so.SoModelInfo;
56 import org.onap.policy.so.SoOperationType;
57 import org.onap.policy.so.SoRequest;
58 import org.onap.policy.so.SoRequestDetails;
59 import org.onap.policy.so.SoResponse;
62 * Operation to delete a VF Module. This gets the VF count from the A&AI Custom Query
63 * response and stores it in the context. It also passes the count-1 to the guard. Once
64 * the "delete" completes successfully, it decrements the VF count that's stored in the
67 public class VfModuleDelete extends SoOperation {
68 public static final String NAME = "VF Module Delete";
70 private static final String PATH_PREFIX = "/";
73 private static final List<String> PROPERTY_NAMES = List.of(
74 OperationProperties.AAI_SERVICE,
75 OperationProperties.AAI_VNF,
76 OperationProperties.AAI_DEFAULT_CLOUD_REGION,
77 OperationProperties.AAI_DEFAULT_TENANT,
78 OperationProperties.DATA_VF_COUNT);
82 * Constructs the object.
84 * @param params operation parameters
85 * @param config configuration for this operation
87 public VfModuleDelete(ControlLoopOperationParams params, HttpPollingConfig config) {
88 super(params, config, PROPERTY_NAMES, params.getTargetEntityIds());
92 // ensure we have the necessary parameters
97 * Ensures that A&AI custom query has been performed, and then runs the guard.
100 @SuppressWarnings("unchecked")
101 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
102 if (params.isPreprocessed()) {
107 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
108 .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
110 // run Custom Query, extract the VF count, and then run the Guard
113 return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams),
114 this::obtainVfCount, this::startGuardAsync);
119 protected Map<String, Object> makeGuardPayload() {
120 Map<String, Object> payload = super.makeGuardPayload();
122 // run guard with the proposed vf count
123 payload.put(PAYLOAD_KEY_VF_COUNT, getVfCount() - 1);
129 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
131 // starting a whole new attempt - reset the count
134 Pair<String, SoRequest> pair = makeRequest();
135 SoRequest request = pair.getRight();
136 String url = getPath() + pair.getLeft();
138 String strRequest = prettyPrint(request);
139 logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
141 Map<String, Object> headers = createSimpleHeaders();
144 return handleResponse(outcome, url,
145 callback -> delete(url, headers, MediaType.APPLICATION_JSON, strRequest, callback));
150 * Issues an HTTP "DELETE" request, containing a request body, using the java built-in
151 * HttpClient, as the JerseyClient does not support it. This will add the content-type
152 * and authorization headers, so they should not be included within "headers".
154 * @param uri URI suffix, to be appended to the URI prefix
155 * @param headers headers to be included
156 * @param contentType content type of the request
157 * @param request request to be posted
158 * @param callback response callbacks
159 * @return a future to await the response. Note: it's untested whether canceling this
160 * future will actually cancel the underlying HTTP request
162 protected CompletableFuture<Response> delete(String uri, Map<String, Object> headers, String contentType,
163 String request, InvocationCallback<Response> callback) {
164 // TODO move to HttpOperation
166 final String url = getClient().getBaseUrl() + uri;
168 Builder builder = HttpRequest.newBuilder(URI.create(url));
169 builder = builder.header("Content-type", contentType);
170 builder = addAuthHeader(builder);
172 for (Entry<String, Object> header : headers.entrySet()) {
173 builder = builder.header(header.getKey(), header.getValue().toString());
176 PipelineControllerFuture<Response> controller = new PipelineControllerFuture<>();
178 HttpRequest req = builder.method("DELETE", BodyPublishers.ofString(request)).build();
180 CompletableFuture<HttpResponse<String>> future = makeHttpClient().sendAsync(req, BodyHandlers.ofString());
182 // propagate "cancel" to the future
183 controller.add(future);
185 future.thenApply(response -> new RestManagerResponse(response.statusCode(), response.body(), getCoder()))
186 .whenComplete((resp, thrown) -> {
187 if (thrown != null) {
188 callback.failed(thrown);
189 controller.completeExceptionally(thrown);
191 callback.completed(resp);
192 controller.complete(resp);
200 * Adds the authorization header to the HTTP request, if configured.
202 * @param builder request builder to which the header should be added
203 * @return the builder
205 protected Builder addAuthHeader(Builder builder) {
206 // TODO move to HttpOperation
207 final HttpClient client = getClient();
208 String username = client.getUserName();
209 if (StringUtils.isBlank(username)) {
213 String password = client.getPassword();
214 if (password == null) {
218 String encoded = username + ":" + password;
219 encoded = Base64.getEncoder().encodeToString(encoded.getBytes(StandardCharsets.UTF_8));
220 return builder.header("Authorization", "Basic " + encoded);
225 * Decrements the VF count that's stored in the context, if the request was
229 protected Status detmStatus(Response rawResponse, SoResponse response) {
230 Status status = super.detmStatus(rawResponse, response);
232 if (status == Status.SUCCESS) {
233 setVfCount(getVfCount() - 1);
242 * @return a pair containing the request URL and the new request
244 protected Pair<String, SoRequest> makeRequest() {
245 final SoModelInfo soModelInfo = prepareSoModelInfo();
246 final GenericVnf vnfItem = getVnfItem(soModelInfo);
247 final ServiceInstance vnfServiceItem = getServiceInstance();
248 final Tenant tenantItem = getDefaultTenant();
249 final CloudRegion cloudRegionItem = getDefaultCloudRegion();
251 SoRequest request = new SoRequest();
252 request.setOperationType(SoOperationType.DELETE_VF_MODULE);
256 // Do NOT send SO the requestId, they do not support this field
258 SoRequestDetails details = new SoRequestDetails();
259 request.setRequestDetails(details);
260 details.setRelatedInstanceList(null);
261 details.setConfigurationParameters(null);
263 // cloudConfiguration
264 details.setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
267 details.setModelInfo(soModelInfo);
270 details.setRequestInfo(constructRequestInfo());
273 * TODO the legacy SO code always passes null for the last argument, though it
274 * should be passing the vfModuleInstanceId
278 String path = PATH_PREFIX + vnfServiceItem.getServiceInstanceId() + "/vnfs/" + vnfItem.getVnfId()
281 return Pair.of(path, request);
284 // these may be overridden by junit tests
286 protected java.net.http.HttpClient makeHttpClient() {
287 return java.net.http.HttpClient.newHttpClient();