09584b487e54c6459192e650eb69a2d145a280bb
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / VfModuleDelete.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.so;
23
24 import java.net.URI;
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;
33 import java.util.Map;
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.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
42 import org.onap.policy.common.endpoints.http.client.HttpClient;
43 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
44 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
46 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
47 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
48 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
49 import org.onap.policy.so.SoOperationType;
50 import org.onap.policy.so.SoRequest;
51 import org.onap.policy.so.SoRequestDetails;
52 import org.onap.policy.so.SoResponse;
53
54 /**
55  * Operation to delete a VF Module. When this completes successfully, it decrements its VF
56  * Count property.
57  */
58 public class VfModuleDelete extends SoOperation {
59     public static final String NAME = "VF Module Delete";
60
61     private static final String PATH_PREFIX = "/";
62
63     // @formatter:off
64     private static final List<String> PROPERTY_NAMES = List.of(
65                             OperationProperties.AAI_SERVICE,
66                             OperationProperties.AAI_VNF,
67                             OperationProperties.AAI_DEFAULT_CLOUD_REGION,
68                             OperationProperties.AAI_DEFAULT_TENANT,
69                             OperationProperties.DATA_VF_COUNT);
70     // @formatter:on
71
72     /**
73      * Constructs the object.
74      *
75      * @param params operation parameters
76      * @param config configuration for this operation
77      */
78     public VfModuleDelete(ControlLoopOperationParams params, HttpPollingConfig config) {
79         super(params, config, PROPERTY_NAMES, params.getTargetEntityIds());
80
81         setUsePolling();
82
83         // ensure we have the necessary parameters
84         validateTarget();
85     }
86
87     @Override
88     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
89
90         // starting a whole new attempt - reset the count
91         resetPollCount();
92
93         Pair<String, SoRequest> pair = makeRequest();
94         SoRequest request = pair.getRight();
95         String url = getPath() + pair.getLeft();
96
97         String strRequest = prettyPrint(request);
98         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
99
100         Map<String, Object> headers = createSimpleHeaders();
101
102         // @formatter:off
103         return handleResponse(outcome, url,
104             callback -> delete(url, headers, MediaType.APPLICATION_JSON, strRequest, callback));
105         // @formatter:on
106     }
107
108     /**
109      * Issues an HTTP "DELETE" request, containing a request body, using the java built-in
110      * HttpClient, as the JerseyClient does not support it. This will add the content-type
111      * and authorization headers, so they should not be included within "headers".
112      *
113      * @param uri URI suffix, to be appended to the URI prefix
114      * @param headers headers to be included
115      * @param contentType content type of the request
116      * @param request request to be posted
117      * @param callback response callbacks
118      * @return a future to await the response. Note: it's untested whether canceling this
119      *         future will actually cancel the underlying HTTP request
120      */
121     protected CompletableFuture<Response> delete(String uri, Map<String, Object> headers, String contentType,
122                     String request, InvocationCallback<Response> callback) {
123         // TODO move to HttpOperation
124
125         final String url = getClient().getBaseUrl() + uri;
126
127         var builder = HttpRequest.newBuilder(URI.create(url));
128         builder = builder.header("Content-type", contentType);
129         builder = addAuthHeader(builder);
130
131         for (Entry<String, Object> header : headers.entrySet()) {
132             builder = builder.header(header.getKey(), header.getValue().toString());
133         }
134
135         PipelineControllerFuture<Response> controller = new PipelineControllerFuture<>();
136
137         HttpRequest req = builder.method("DELETE", BodyPublishers.ofString(request)).build();
138
139         CompletableFuture<HttpResponse<String>> future = makeHttpClient().sendAsync(req, BodyHandlers.ofString());
140
141         // propagate "cancel" to the future
142         controller.add(future);
143
144         future.thenApply(response -> new RestManagerResponse(response.statusCode(), response.body(), getCoder()))
145                         .whenComplete((resp, thrown) -> {
146                             if (thrown != null) {
147                                 callback.failed(thrown);
148                                 controller.completeExceptionally(thrown);
149                             } else {
150                                 callback.completed(resp);
151                                 controller.complete(resp);
152                             }
153                         });
154
155         return controller;
156     }
157
158     /**
159      * Adds the authorization header to the HTTP request, if configured.
160      *
161      * @param builder request builder to which the header should be added
162      * @return the builder
163      */
164     protected Builder addAuthHeader(Builder builder) {
165         // TODO move to HttpOperation
166         final HttpClient client = getClient();
167         String username = client.getUserName();
168         if (StringUtils.isBlank(username)) {
169             return builder;
170         }
171
172         String password = client.getPassword();
173         if (password == null) {
174             password = "";
175         }
176
177         String encoded = username + ":" + password;
178         encoded = Base64.getEncoder().encodeToString(encoded.getBytes(StandardCharsets.UTF_8));
179         return builder.header("Authorization", "Basic " + encoded);
180     }
181
182
183     /**
184      * Decrements the VF count that's stored in the context, if the request was
185      * successful.
186      */
187     @Override
188     protected Status detmStatus(Response rawResponse, SoResponse response) {
189         var status = super.detmStatus(rawResponse, response);
190
191         if (status == Status.SUCCESS) {
192             setVfCount(getVfCount() - 1);
193         }
194
195         return status;
196     }
197
198     /**
199      * Makes a request.
200      *
201      * @return a pair containing the request URL and the new request
202      */
203     protected Pair<String, SoRequest> makeRequest() {
204         final var soModelInfo = prepareSoModelInfo();
205         final var vnfItem = getVnfItem();
206         final var vnfServiceItem = getServiceInstance();
207         final var tenantItem = getDefaultTenant();
208         final var cloudRegionItem = getDefaultCloudRegion();
209
210         var request = new SoRequest();
211         request.setOperationType(SoOperationType.DELETE_VF_MODULE);
212
213         //
214         //
215         // Do NOT send SO the requestId, they do not support this field
216         //
217         var details = new SoRequestDetails();
218         request.setRequestDetails(details);
219         details.setRelatedInstanceList(null);
220         details.setConfigurationParameters(null);
221
222         // cloudConfiguration
223         details.setCloudConfiguration(constructCloudConfiguration(tenantItem, cloudRegionItem));
224
225         // modelInfo
226         details.setModelInfo(soModelInfo);
227
228         // requestInfo
229         details.setRequestInfo(constructRequestInfo());
230
231         /*
232          * TODO the legacy SO code always passes null for the last argument, though it
233          * should be passing the vfModuleInstanceId
234          */
235
236         // compute the path
237         String svcId = getRequiredText("service instance ID", vnfServiceItem.getServiceInstanceId());
238         String path = PATH_PREFIX + svcId + "/vnfs/" + vnfItem.getVnfId() + "/vfModules/null";
239
240         return Pair.of(path, request);
241     }
242
243     // these may be overridden by junit tests
244
245     protected java.net.http.HttpClient makeHttpClient() {
246         return java.net.http.HttpClient.newHttpClient();
247     }
248 }