c67243f9f8e8643b568fdabe612f961d1bf76409
[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 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.so;
22
23 import java.net.URI;
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;
31 import java.util.Map;
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.controlloop.actorserviceprovider.OperationOutcome;
49 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
50 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
51 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
52 import org.onap.policy.so.SoModelInfo;
53 import org.onap.policy.so.SoOperationType;
54 import org.onap.policy.so.SoRequest;
55 import org.onap.policy.so.SoRequestDetails;
56 import org.onap.policy.so.SoResponse;
57
58 /**
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
62  * context.
63  */
64 public class VfModuleDelete extends SoOperation {
65     public static final String NAME = "VF Module Delete";
66
67     private static final String PATH_PREFIX = "/";
68
69     /**
70      * Constructs the object.
71      *
72      * @param params operation parameters
73      * @param config configuration for this operation
74      */
75     public VfModuleDelete(ControlLoopOperationParams params, HttpPollingConfig config) {
76         super(params, config);
77
78         // ensure we have the necessary parameters
79         validateTarget();
80     }
81
82     /**
83      * Ensures that A&AI custom query has been performed, and then runs the guard.
84      */
85     @Override
86     @SuppressWarnings("unchecked")
87     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
88
89         // need the VF count
90         ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
91                         .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
92
93         // run Custom Query, extract the VF count, and then run the Guard
94
95         // @formatter:off
96         return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams),
97                         this::obtainVfCount, this::startGuardAsync);
98         // @formatter:on
99     }
100
101     @Override
102     protected Map<String, Object> makeGuardPayload() {
103         Map<String, Object> payload = super.makeGuardPayload();
104
105         // run guard with the proposed vf count
106         payload.put(PAYLOAD_KEY_VF_COUNT, getVfCount() - 1);
107
108         return payload;
109     }
110
111     @Override
112     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
113
114         // starting a whole new attempt - reset the count
115         resetPollCount();
116
117         Pair<String, SoRequest> pair = makeRequest();
118         SoRequest request = pair.getRight();
119         String url = getPath() + pair.getLeft();
120
121         String strRequest = prettyPrint(request);
122         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
123
124         Map<String, Object> headers = createSimpleHeaders();
125
126         // @formatter:off
127         return handleResponse(outcome, url,
128             callback -> delete(url, headers, MediaType.APPLICATION_JSON, strRequest, callback));
129         // @formatter:on
130     }
131
132     /**
133      * Issues an HTTP "DELETE" request, containing a request body, using the java built-in
134      * HttpClient, as the JerseyClient does not support it. This will add the content-type
135      * and authorization headers, so they should not be included within "headers".
136      *
137      * @param <Q> request type
138      * @param uri URI suffix, to be appended to the URI prefix
139      * @param headers headers to be included
140      * @param contentType content type of the request
141      * @param request request to be posted
142      * @param callback response callbacks
143      * @return a future to await the response. Note: it's untested whether canceling this
144      *         future will actually cancel the underlying HTTP request
145      */
146     protected <Q> CompletableFuture<Response> delete(String uri, Map<String, Object> headers, String contentType,
147                     String request, InvocationCallback<Response> callback) {
148         // TODO move to HttpOperation
149
150         final String url = getClient().getBaseUrl() + uri;
151
152         Builder builder = HttpRequest.newBuilder(URI.create(url));
153         builder = builder.header("Content-type", contentType);
154         builder = addAuthHeader(builder);
155
156         for (Entry<String, Object> header : headers.entrySet()) {
157             builder = builder.header(header.getKey(), header.getValue().toString());
158         }
159
160         PipelineControllerFuture<Response> controller = new PipelineControllerFuture<>();
161
162         HttpRequest req = builder.method("DELETE", BodyPublishers.ofString(request)).build();
163
164         CompletableFuture<HttpResponse<String>> future = makeHttpClient().sendAsync(req, BodyHandlers.ofString());
165
166         // propagate "cancel" to the future
167         controller.add(future);
168
169         future.thenApply(response -> new RestManagerResponse(response.statusCode(), response.body(), getCoder()))
170                         .whenComplete((resp, thrown) -> {
171                             if (thrown != null) {
172                                 callback.failed(thrown);
173                                 controller.completeExceptionally(thrown);
174                             } else {
175                                 callback.completed(resp);
176                                 controller.complete(resp);
177                             }
178                         });
179
180         return controller;
181     }
182
183     /**
184      * Adds the authorization header to the HTTP request, if configured.
185      *
186      * @param builder request builder to which the header should be added
187      * @return the builder
188      */
189     protected Builder addAuthHeader(Builder builder) {
190         // TODO move to HttpOperation
191         final HttpClient client = getClient();
192         String username = client.getUserName();
193         if (StringUtils.isBlank(username)) {
194             return builder;
195         }
196
197         String password = client.getPassword();
198         if (password == null) {
199             password = "";
200         }
201
202         String encoded = username + ":" + password;
203         encoded = Base64.getEncoder().encodeToString(encoded.getBytes(StandardCharsets.UTF_8));
204         return builder.header("Authorization", "Basic " + encoded);
205     }
206
207
208     /**
209      * Decrements the VF count that's stored in the context, if the request was
210      * successful.
211      */
212     @Override
213     protected Status detmStatus(Response rawResponse, SoResponse response) {
214         Status status = super.detmStatus(rawResponse, response);
215
216         if (status == Status.SUCCESS) {
217             setVfCount(getVfCount() - 1);
218         }
219
220         return status;
221     }
222
223     /**
224      * Makes a request.
225      *
226      * @return a pair containing the request URL and the new request
227      */
228     protected Pair<String, SoRequest> makeRequest() {
229         final AaiCqResponse aaiCqResponse = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
230         final SoModelInfo soModelInfo = prepareSoModelInfo();
231         final GenericVnf vnfItem = getVnfItem(aaiCqResponse, soModelInfo);
232         final ServiceInstance vnfServiceItem = getServiceInstance(aaiCqResponse);
233         final Tenant tenantItem = getDefaultTenant(aaiCqResponse);
234         final CloudRegion cloudRegionItem = getDefaultCloudRegion(aaiCqResponse);
235
236         SoRequest request = new SoRequest();
237         request.setOperationType(SoOperationType.DELETE_VF_MODULE);
238
239         //
240         //
241         // Do NOT send SO the requestId, they do not support this field
242         //
243         SoRequestDetails details = new SoRequestDetails();
244         request.setRequestDetails(details);
245         details.setRelatedInstanceList(null);
246         details.setConfigurationParameters(null);
247
248         // cloudConfiguration
249         details.setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
250
251         // modelInfo
252         details.setModelInfo(soModelInfo);
253
254         // requestInfo
255         details.setRequestInfo(constructRequestInfo());
256
257         /*
258          * TODO the legacy SO code always passes null for the last argument, though it
259          * should be passing the vfModuleInstanceId
260          */
261
262         // compute the path
263         String path = PATH_PREFIX + vnfServiceItem.getServiceInstanceId() + "/vnfs/" + vnfItem.getVnfId()
264                         + "/vfModules/null";
265
266         return Pair.of(path, request);
267     }
268
269     // these may be overridden by junit tests
270
271     protected java.net.http.HttpClient makeHttpClient() {
272         return java.net.http.HttpClient.newHttpClient();
273     }
274 }