f35cdb4e1b8446cf530343885b0ce7da3f8d16ea
[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  * 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.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;
60
61 /**
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
65  * context.
66  */
67 public class VfModuleDelete extends SoOperation {
68     public static final String NAME = "VF Module Delete";
69
70     private static final String PATH_PREFIX = "/";
71
72     // @formatter:off
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);
79     // @formatter:on
80
81     /**
82      * Constructs the object.
83      *
84      * @param params operation parameters
85      * @param config configuration for this operation
86      */
87     public VfModuleDelete(ControlLoopOperationParams params, HttpPollingConfig config) {
88         super(params, config, PROPERTY_NAMES, params.getTargetEntityIds());
89
90         setUsePolling();
91
92         // ensure we have the necessary parameters
93         validateTarget();
94     }
95
96     /**
97      * Ensures that A&AI custom query has been performed, and then runs the guard.
98      */
99     @Override
100     @SuppressWarnings("unchecked")
101     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
102         if (params.isPreprocessed()) {
103             return null;
104         }
105
106         // need the VF count
107         ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
108                         .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
109
110         // run Custom Query, extract the VF count, and then run the Guard
111
112         // @formatter:off
113         return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams),
114                         this::obtainVfCount, this::startGuardAsync);
115         // @formatter:on
116     }
117
118     @Override
119     protected Map<String, Object> makeGuardPayload() {
120         Map<String, Object> payload = super.makeGuardPayload();
121
122         // run guard with the proposed vf count
123         payload.put(PAYLOAD_KEY_VF_COUNT, getVfCount() - 1);
124
125         return payload;
126     }
127
128     @Override
129     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
130
131         // starting a whole new attempt - reset the count
132         resetPollCount();
133
134         Pair<String, SoRequest> pair = makeRequest();
135         SoRequest request = pair.getRight();
136         String url = getPath() + pair.getLeft();
137
138         String strRequest = prettyPrint(request);
139         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
140
141         Map<String, Object> headers = createSimpleHeaders();
142
143         // @formatter:off
144         return handleResponse(outcome, url,
145             callback -> delete(url, headers, MediaType.APPLICATION_JSON, strRequest, callback));
146         // @formatter:on
147     }
148
149     /**
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".
153      *
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
161      */
162     protected CompletableFuture<Response> delete(String uri, Map<String, Object> headers, String contentType,
163                     String request, InvocationCallback<Response> callback) {
164         // TODO move to HttpOperation
165
166         final String url = getClient().getBaseUrl() + uri;
167
168         Builder builder = HttpRequest.newBuilder(URI.create(url));
169         builder = builder.header("Content-type", contentType);
170         builder = addAuthHeader(builder);
171
172         for (Entry<String, Object> header : headers.entrySet()) {
173             builder = builder.header(header.getKey(), header.getValue().toString());
174         }
175
176         PipelineControllerFuture<Response> controller = new PipelineControllerFuture<>();
177
178         HttpRequest req = builder.method("DELETE", BodyPublishers.ofString(request)).build();
179
180         CompletableFuture<HttpResponse<String>> future = makeHttpClient().sendAsync(req, BodyHandlers.ofString());
181
182         // propagate "cancel" to the future
183         controller.add(future);
184
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);
190                             } else {
191                                 callback.completed(resp);
192                                 controller.complete(resp);
193                             }
194                         });
195
196         return controller;
197     }
198
199     /**
200      * Adds the authorization header to the HTTP request, if configured.
201      *
202      * @param builder request builder to which the header should be added
203      * @return the builder
204      */
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)) {
210             return builder;
211         }
212
213         String password = client.getPassword();
214         if (password == null) {
215             password = "";
216         }
217
218         String encoded = username + ":" + password;
219         encoded = Base64.getEncoder().encodeToString(encoded.getBytes(StandardCharsets.UTF_8));
220         return builder.header("Authorization", "Basic " + encoded);
221     }
222
223
224     /**
225      * Decrements the VF count that's stored in the context, if the request was
226      * successful.
227      */
228     @Override
229     protected Status detmStatus(Response rawResponse, SoResponse response) {
230         Status status = super.detmStatus(rawResponse, response);
231
232         if (status == Status.SUCCESS) {
233             setVfCount(getVfCount() - 1);
234         }
235
236         return status;
237     }
238
239     /**
240      * Makes a request.
241      *
242      * @return a pair containing the request URL and the new request
243      */
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();
250
251         SoRequest request = new SoRequest();
252         request.setOperationType(SoOperationType.DELETE_VF_MODULE);
253
254         //
255         //
256         // Do NOT send SO the requestId, they do not support this field
257         //
258         SoRequestDetails details = new SoRequestDetails();
259         request.setRequestDetails(details);
260         details.setRelatedInstanceList(null);
261         details.setConfigurationParameters(null);
262
263         // cloudConfiguration
264         details.setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
265
266         // modelInfo
267         details.setModelInfo(soModelInfo);
268
269         // requestInfo
270         details.setRequestInfo(constructRequestInfo());
271
272         /*
273          * TODO the legacy SO code always passes null for the last argument, though it
274          * should be passing the vfModuleInstanceId
275          */
276
277         // compute the path
278         String path = PATH_PREFIX + vnfServiceItem.getServiceInstanceId() + "/vnfs/" + vnfItem.getVnfId()
279                         + "/vfModules/null";
280
281         return Pair.of(path, request);
282     }
283
284     // these may be overridden by junit tests
285
286     protected java.net.http.HttpClient makeHttpClient() {
287         return java.net.http.HttpClient.newHttpClient();
288     }
289 }