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