Add SO VF Module Delete Operation
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / SoOperation.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.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.concurrent.CompletableFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Function;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.Response;
33 import lombok.Getter;
34 import org.onap.aai.domain.yang.CloudRegion;
35 import org.onap.aai.domain.yang.GenericVnf;
36 import org.onap.aai.domain.yang.ServiceInstance;
37 import org.onap.aai.domain.yang.Tenant;
38 import org.onap.policy.aai.AaiConstants;
39 import org.onap.policy.aai.AaiCqResponse;
40 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
42 import org.onap.policy.common.utils.coder.Coder;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
46 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
47 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
48 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
49 import org.onap.policy.controlloop.policy.PolicyResult;
50 import org.onap.policy.controlloop.policy.Target;
51 import org.onap.policy.so.SoCloudConfiguration;
52 import org.onap.policy.so.SoModelInfo;
53 import org.onap.policy.so.SoRequest;
54 import org.onap.policy.so.SoRequestInfo;
55 import org.onap.policy.so.SoRequestParameters;
56 import org.onap.policy.so.SoRequestStatus;
57 import org.onap.policy.so.SoResponse;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 /**
62  * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetGetCount()}
63  * each time they issue an HTTP request.
64  */
65 public abstract class SoOperation extends HttpOperation<SoResponse> {
66     private static final Logger logger = LoggerFactory.getLogger(SoOperation.class);
67     private static final Coder coder = new StandardCoder();
68
69     public static final String PAYLOAD_KEY_VF_COUNT = "vfCount";
70     public static final String FAILED = "FAILED";
71     public static final String COMPLETE = "COMPLETE";
72     public static final int SO_RESPONSE_CODE = 999;
73
74     // fields within the policy payload
75     public static final String REQ_PARAM_NM = "requestParameters";
76     public static final String CONFIG_PARAM_NM = "configurationParameters";
77
78     private final SoConfig config;
79
80     // values extracted from the parameter Target
81     private final String modelCustomizationId;
82     private final String modelInvariantId;
83     private final String modelVersionId;
84
85     private final String vfCountKey;
86
87     /**
88      * Number of "get" requests issued so far, on the current operation attempt.
89      */
90     @Getter
91     private int getCount;
92
93
94     /**
95      * Constructs the object.
96      *
97      * @param params operation parameters
98      * @param config configuration for this operation
99      */
100     public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
101         super(params, config, SoResponse.class);
102         this.config = (SoConfig) config;
103
104         verifyNotNull("Target information", params.getTarget());
105
106         this.modelCustomizationId = params.getTarget().getModelCustomizationId();
107         this.modelInvariantId = params.getTarget().getModelInvariantId();
108         this.modelVersionId = params.getTarget().getModelVersionId();
109
110         vfCountKey = SoConstants.VF_COUNT_PREFIX + "[" + modelCustomizationId + "][" + modelInvariantId + "]["
111                         + modelVersionId + "]";
112     }
113
114     /**
115      * Subclasses should invoke this before issuing their first HTTP request.
116      */
117     protected void resetGetCount() {
118         getCount = 0;
119     }
120
121     /**
122      * Validates that the parameters contain the required target information to extract
123      * the VF count from the custom query.
124      */
125     protected void validateTarget() {
126         verifyNotNull("model-customization-id", modelCustomizationId);
127         verifyNotNull("model-invariant-id", modelInvariantId);
128         verifyNotNull("model-version-id", modelVersionId);
129     }
130
131     private void verifyNotNull(String type, Object value) {
132         if (value == null) {
133             throw new IllegalArgumentException("missing " + type + " for guard payload");
134         }
135     }
136
137     /**
138      * Starts the GUARD.
139      */
140     @Override
141     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
142         return startGuardAsync();
143     }
144
145     /**
146      * Gets the VF Count.
147      *
148      * @return a future to cancel or await the VF Count
149      */
150     @SuppressWarnings("unchecked")
151     protected CompletableFuture<OperationOutcome> obtainVfCount() {
152         if (params.getContext().contains(vfCountKey)) {
153             // already have the VF count
154             return null;
155         }
156
157         // need custom query from which to extract the VF count
158         ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
159                         .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
160
161         // run Custom Query and then extract the VF count
162         return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::storeVfCount);
163     }
164
165     /**
166      * Stores the VF count.
167      *
168      * @return {@code null}
169      */
170     private CompletableFuture<OperationOutcome> storeVfCount() {
171         if (!params.getContext().contains(vfCountKey)) {
172             AaiCqResponse cq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
173             int vfcount = cq.getVfModuleCount(modelCustomizationId, modelInvariantId, modelVersionId);
174
175             params.getContext().setProperty(vfCountKey, vfcount);
176         }
177
178         return null;
179     }
180
181     protected int getVfCount() {
182         return params.getContext().getProperty(vfCountKey);
183     }
184
185     protected void setVfCount(int vfCount) {
186         params.getContext().setProperty(vfCountKey, vfCount);
187     }
188
189     /**
190      * If the response does not indicate that the request has been completed, then sleep a
191      * bit and issue a "get".
192      */
193     @Override
194     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
195                     Response rawResponse, SoResponse response) {
196
197         // see if the request has "completed", whether or not it was successful
198         if (rawResponse.getStatus() == 200) {
199             String requestState = getRequestState(response);
200             if (COMPLETE.equalsIgnoreCase(requestState)) {
201                 successfulCompletion();
202                 return CompletableFuture
203                                 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
204             }
205
206             if (FAILED.equalsIgnoreCase(requestState)) {
207                 return CompletableFuture
208                                 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
209             }
210         }
211
212         // still incomplete
213
214         // need a request ID with which to query
215         if (response == null || response.getRequestReferences() == null
216                         || response.getRequestReferences().getRequestId() == null) {
217             throw new IllegalArgumentException("missing request ID in response");
218         }
219
220         // see if the limit for the number of "gets" has been reached
221         if (getCount++ >= getMaxGets()) {
222             logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
223             setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
224             outcome.setMessage(SO_RESPONSE_CODE + " " + outcome.getMessage());
225             return CompletableFuture.completedFuture(outcome);
226         }
227
228         // sleep and then perform a "get" operation
229         Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
230         return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
231     }
232
233     /**
234      * Invoked when a request completes successfully.
235      */
236     protected void successfulCompletion() {
237         // do nothing
238     }
239
240     /**
241      * Issues a "get" request to see if the original request is complete yet.
242      *
243      * @param outcome outcome to be populated with the response
244      * @param response previous response
245      * @return a future that can be used to cancel the "get" request or await its response
246      */
247     private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, SoResponse response) {
248         String path = getPathGet() + response.getRequestReferences().getRequestId();
249         String url = getClient().getBaseUrl() + path;
250
251         logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
252
253         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
254
255         // TODO should this use "path" or the full "url"?
256         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
257     }
258
259     /**
260      * Gets the request state of a response.
261      *
262      * @param response response from which to get the state
263      * @return the request state of the response, or {@code null} if it does not exist
264      */
265     protected String getRequestState(SoResponse response) {
266         SoRequest request = response.getRequest();
267         if (request == null) {
268             return null;
269         }
270
271         SoRequestStatus status = request.getRequestStatus();
272         if (status == null) {
273             return null;
274         }
275
276         return status.getRequestState();
277     }
278
279     /**
280      * Treats everything as a success, so we always go into
281      * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
282      */
283     @Override
284     protected boolean isSuccess(Response rawResponse, SoResponse response) {
285         return true;
286     }
287
288     /**
289      * Prepends the message with the http status code.
290      */
291     @Override
292     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
293                     SoResponse response) {
294
295         // set default result and message
296         setOutcome(outcome, result);
297
298         outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
299         return outcome;
300     }
301
302     protected SoModelInfo prepareSoModelInfo() {
303         Target target = params.getTarget();
304         if (target == null) {
305             throw new IllegalArgumentException("missing Target");
306         }
307
308         if (target.getModelCustomizationId() == null || target.getModelInvariantId() == null
309                         || target.getModelName() == null || target.getModelVersion() == null
310                         || target.getModelVersionId() == null) {
311             throw new IllegalArgumentException("missing VF Module model");
312         }
313
314         SoModelInfo soModelInfo = new SoModelInfo();
315         soModelInfo.setModelCustomizationId(target.getModelCustomizationId());
316         soModelInfo.setModelInvariantId(target.getModelInvariantId());
317         soModelInfo.setModelName(target.getModelName());
318         soModelInfo.setModelVersion(target.getModelVersion());
319         soModelInfo.setModelVersionId(target.getModelVersionId());
320         soModelInfo.setModelType("vfModule");
321         return soModelInfo;
322     }
323
324     /**
325      * Construct requestInfo for the SO requestDetails.
326      *
327      * @return SO request information
328      */
329     protected SoRequestInfo constructRequestInfo() {
330         SoRequestInfo soRequestInfo = new SoRequestInfo();
331         soRequestInfo.setSource("POLICY");
332         soRequestInfo.setSuppressRollback(false);
333         soRequestInfo.setRequestorId("policy");
334         return soRequestInfo;
335     }
336
337     /**
338      * Builds the request parameters from the policy payload.
339      */
340     protected Optional<SoRequestParameters> buildRequestParameters() {
341         if (params.getPayload() == null) {
342             return Optional.empty();
343         }
344
345         Object data = params.getPayload().get(REQ_PARAM_NM);
346         if (data == null) {
347             return Optional.empty();
348         }
349
350         try {
351             return Optional.of(coder.decode(data.toString(), SoRequestParameters.class));
352         } catch (CoderException e) {
353             throw new IllegalArgumentException("invalid payload value: " + REQ_PARAM_NM);
354         }
355     }
356
357     /**
358      * Builds the configuration parameters from the policy payload.
359      */
360     protected Optional<List<Map<String, String>>> buildConfigurationParameters() {
361         if (params.getPayload() == null) {
362             return Optional.empty();
363         }
364
365         Object data = params.getPayload().get(CONFIG_PARAM_NM);
366         if (data == null) {
367             return Optional.empty();
368         }
369
370         try {
371             @SuppressWarnings("unchecked")
372             List<Map<String, String>> result = coder.decode(data.toString(), ArrayList.class);
373             return Optional.of(result);
374         } catch (CoderException | RuntimeException e) {
375             throw new IllegalArgumentException("invalid payload value: " + CONFIG_PARAM_NM);
376         }
377     }
378
379     /**
380      * Construct cloudConfiguration for the SO requestDetails. Overridden for custom
381      * query.
382      *
383      * @param tenantItem tenant item from A&AI named-query response
384      * @return SO cloud configuration
385      */
386     protected SoCloudConfiguration constructCloudConfigurationCq(Tenant tenantItem, CloudRegion cloudRegionItem) {
387         SoCloudConfiguration cloudConfiguration = new SoCloudConfiguration();
388         cloudConfiguration.setTenantId(tenantItem.getTenantId());
389         cloudConfiguration.setLcpCloudRegionId(cloudRegionItem.getCloudRegionId());
390         return cloudConfiguration;
391     }
392
393     /**
394      * Create simple HTTP headers for unauthenticated requests to SO.
395      *
396      * @return the HTTP headers
397      */
398     protected Map<String, Object> createSimpleHeaders() {
399         Map<String, Object> headers = new HashMap<>();
400         headers.put("Accept", MediaType.APPLICATION_JSON);
401         return headers;
402     }
403
404     /*
405      * These methods extract data from the Custom Query and throw an
406      * IllegalArgumentException if the desired data item is not found.
407      */
408
409     protected GenericVnf getVnfItem(AaiCqResponse aaiCqResponse, SoModelInfo soModelInfo) {
410         GenericVnf vnf = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
411         if (vnf == null) {
412             throw new IllegalArgumentException("missing generic VNF");
413         }
414
415         return vnf;
416     }
417
418     protected ServiceInstance getServiceInstance(AaiCqResponse aaiCqResponse) {
419         ServiceInstance vnfService = aaiCqResponse.getServiceInstance();
420         if (vnfService == null) {
421             throw new IllegalArgumentException("missing VNF Service Item");
422         }
423
424         return vnfService;
425     }
426
427     protected Tenant getDefaultTenant(AaiCqResponse aaiCqResponse) {
428         Tenant tenant = aaiCqResponse.getDefaultTenant();
429         if (tenant == null) {
430             throw new IllegalArgumentException("missing Tenant Item");
431         }
432
433         return tenant;
434     }
435
436     protected CloudRegion getDefaultCloudRegion(AaiCqResponse aaiCqResponse) {
437         CloudRegion cloudRegion = aaiCqResponse.getDefaultCloudRegion();
438         if (cloudRegion == null) {
439             throw new IllegalArgumentException("missing Cloud Region");
440         }
441
442         return cloudRegion;
443     }
444
445     // these may be overridden by junit tests
446
447     /**
448      * Gets the wait time, in milliseconds, between "get" requests.
449      *
450      * @return the wait time, in milliseconds, between "get" requests
451      */
452     public long getWaitMsGet() {
453         return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
454     }
455
456     public int getMaxGets() {
457         return config.getMaxGets();
458     }
459
460     public String getPathGet() {
461         return config.getPathGet();
462     }
463
464     public int getWaitSecGet() {
465         return config.getWaitSecGet();
466     }
467 }