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