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;
24 import java.net.http.HttpRequest;
25 import java.net.http.HttpRequest.BodyPublishers;
26 import java.net.http.HttpRequest.Builder;
27 import java.net.http.HttpResponse;
28 import java.net.http.HttpResponse.BodyHandlers;
29 import java.nio.charset.StandardCharsets;
30 import java.util.Base64;
32 import java.util.Map.Entry;
33 import java.util.concurrent.CompletableFuture;
34 import javax.ws.rs.client.InvocationCallback;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37 import org.apache.commons.lang3.StringUtils;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.onap.aai.domain.yang.CloudRegion;
40 import org.onap.aai.domain.yang.GenericVnf;
41 import org.onap.aai.domain.yang.ServiceInstance;
42 import org.onap.aai.domain.yang.Tenant;
43 import org.onap.policy.aai.AaiConstants;
44 import org.onap.policy.aai.AaiCqResponse;
45 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
46 import org.onap.policy.common.endpoints.http.client.HttpClient;
47 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
50 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
51 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
52 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
53 import org.onap.policy.so.SoModelInfo;
54 import org.onap.policy.so.SoOperationType;
55 import org.onap.policy.so.SoRequest;
56 import org.onap.policy.so.SoRequestDetails;
59 * Operation to delete a VF Module. This gets the VF count from the A&AI Custom Query
60 * response and stores it in the context. It also passes the count-1 to the guard. Once
61 * the "delete" completes successfully, it decrements the VF count that's stored in the
64 public class VfModuleDelete extends SoOperation {
65 public static final String NAME = "VF Module Delete";
67 private static final String PATH_PREFIX = "/";
70 * Constructs the object.
72 * @param params operation parameters
73 * @param config configuration for this operation
75 public VfModuleDelete(ControlLoopOperationParams params, HttpConfig config) {
76 super(params, config);
78 // ensure we have the necessary parameters
83 * Ensures that A&AI custom query has been performed, and then runs the guard.
86 @SuppressWarnings("unchecked")
87 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
90 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
91 .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
93 // run Custom Query, extract the VF count, and then run the Guard
96 return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams),
97 this::obtainVfCount, this::startGuardAsync);
102 protected Map<String, Object> makeGuardPayload() {
103 Map<String, Object> payload = super.makeGuardPayload();
105 // run guard with the proposed vf count
106 payload.put(PAYLOAD_KEY_VF_COUNT, getVfCount() - 1);
112 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
114 // starting a whole new attempt - reset the count
117 Pair<String, SoRequest> pair = makeRequest();
118 SoRequest request = pair.getRight();
119 String url = getPath() + pair.getLeft();
121 logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
123 Map<String, Object> headers = createSimpleHeaders();
126 return handleResponse(outcome, url,
127 callback -> delete(url, headers, MediaType.APPLICATION_JSON, request, callback));
132 * Issues an HTTP "DELETE" request, containing a request body, using the java built-in
133 * HttpClient, as the JerseyClient does not support it. This will add the content-type
134 * and authorization headers, so they should not be included within "headers".
136 * @param <Q> request type
137 * @param uri URI suffix, to be appended to the URI prefix
138 * @param headers headers to be included
139 * @param contentType content type of the request
140 * @param request request to be posted
141 * @param callback response callbacks
142 * @return a future to await the response. Note: it's untested whether canceling this
143 * future will actually cancel the underlying HTTP request
145 protected <Q> CompletableFuture<Response> delete(String uri, Map<String, Object> headers, String contentType,
146 Q request, InvocationCallback<Response> callback) {
147 // TODO move to HttpOperation
149 // make sure we can encode it before going any further
150 final String body = encodeRequest(request);
152 final String url = getClient().getBaseUrl() + uri;
154 Builder builder = HttpRequest.newBuilder(URI.create(url));
155 builder = builder.header("Content-type", contentType);
156 builder = addAuthHeader(builder);
158 for (Entry<String, Object> header : headers.entrySet()) {
159 builder = builder.header(header.getKey(), header.getValue().toString());
162 PipelineControllerFuture<Response> controller = new PipelineControllerFuture<>();
164 HttpRequest req = builder.method("DELETE", BodyPublishers.ofString(body)).build();
166 CompletableFuture<HttpResponse<String>> future = makeHttpClient().sendAsync(req, BodyHandlers.ofString());
168 // propagate "cancel" to the future
169 controller.add(future);
171 future.thenApply(response -> new RestManagerResponse(response.statusCode(), response.body(), makeCoder()))
172 .whenComplete((resp, thrown) -> {
173 if (thrown != null) {
174 callback.failed(thrown);
175 controller.completeExceptionally(thrown);
177 callback.completed(resp);
178 controller.complete(resp);
188 * @param <Q> request type
189 * @param request request to be encoded
190 * @return the encoded request
192 protected <Q> String encodeRequest(Q request) {
193 // TODO move to HttpOperation
195 if (request instanceof String) {
196 return request.toString();
198 return makeCoder().encode(request);
200 } catch (CoderException e) {
201 throw new IllegalArgumentException("cannot encode request", e);
206 * Adds the authorization header to the HTTP request, if configured.
208 * @param builder request builder to which the header should be added
209 * @return the builder
211 protected Builder addAuthHeader(Builder builder) {
212 // TODO move to HttpOperation
213 final HttpClient client = getClient();
214 String username = client.getUserName();
215 if (StringUtils.isBlank(username)) {
219 String password = client.getPassword();
220 if (password == null) {
224 String encoded = username + ":" + password;
225 encoded = Base64.getEncoder().encodeToString(encoded.getBytes(StandardCharsets.UTF_8));
226 return builder.header("Authorization", "Basic " + encoded);
230 * Decrements the VF count that's stored in the context.
233 protected void successfulCompletion() {
234 setVfCount(getVfCount() - 1);
240 * @return a pair containing the request URL and the new request
242 protected Pair<String, SoRequest> makeRequest() {
243 final AaiCqResponse aaiCqResponse = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
244 final SoModelInfo soModelInfo = prepareSoModelInfo();
245 final GenericVnf vnfItem = getVnfItem(aaiCqResponse, soModelInfo);
246 final ServiceInstance vnfServiceItem = getServiceInstance(aaiCqResponse);
247 final Tenant tenantItem = getDefaultTenant(aaiCqResponse);
248 final CloudRegion cloudRegionItem = getDefaultCloudRegion(aaiCqResponse);
250 SoRequest request = new SoRequest();
251 request.setOperationType(SoOperationType.DELETE_VF_MODULE);
255 // Do NOT send SO the requestId, they do not support this field
257 SoRequestDetails details = new SoRequestDetails();
258 request.setRequestDetails(details);
259 details.setRelatedInstanceList(null);
260 details.setConfigurationParameters(null);
262 // cloudConfiguration
263 details.setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
266 details.setModelInfo(soModelInfo);
269 details.setRequestInfo(constructRequestInfo());
272 * TODO the legacy SO code always passes null for the last argument, though it
273 * should be passing the vfModuleInstanceId
277 String path = PATH_PREFIX + vnfServiceItem.getServiceInstanceId() + "/vnfs/" + vnfItem.getVnfId()
280 return Pair.of(path, request);
283 // these may be overridden by junit tests
285 protected java.net.http.HttpClient makeHttpClient() {
286 return java.net.http.HttpClient.newHttpClient();