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