Restore interrupted state
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / dal / ActiveInventoryAdapter.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
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 package org.onap.aai.sparky.dal;
22
23 import java.io.IOException;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.net.URLEncoder;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.NoSuchElementException;
32
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.UriBuilder;
35
36 import org.apache.http.client.utils.URIBuilder;
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.restclient.client.OperationResult;
40 import org.onap.aai.restclient.client.RestClient;
41 import org.onap.aai.restclient.enums.RestAuthenticationMode;
42 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
43 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
44 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
45 import org.onap.aai.sparky.dal.exception.ElasticSearchOperationException;
46 import org.onap.aai.sparky.dal.rest.RestClientConstructionException;
47 import org.onap.aai.sparky.dal.rest.RestClientFactory;
48 import org.onap.aai.sparky.dal.rest.config.RestEndpointConfig;
49 import org.onap.aai.sparky.logging.AaiUiMsgs;
50 import org.onap.aai.sparky.util.Encryptor;
51 import org.onap.aai.sparky.util.NodeUtils;
52 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
53
54 /**
55  * The Class ActiveInventoryAdapter.
56  */
57
58 public class ActiveInventoryAdapter {
59
60   private static final Logger LOG =
61       LoggerFactory.getInstance().getLogger(ActiveInventoryAdapter.class);
62
63   private static final String HEADER_TRANS_ID = "X-TransactionId";
64   private static final String HEADER_FROM_APP_ID = "X-FromAppId";
65   private static final String HEADER_AUTHORIZATION = "Authorization";
66
67   private static final String HTTP_SCHEME = "http";
68   private static final String HTTPS_SCHEME = "https";
69   
70   private static final String TRANSACTION_ID_PREFIX = "txnId-";
71   private static final String UI_APP_NAME = "AAI-UI";
72
73   private OxmModelLoader oxmModelLoader;
74   private OxmEntityLookup oxmEntityLookup;
75   private RestEndpointConfig endpointConfig; 
76
77   private RestClient restClient;
78
79   /**
80    * Instantiates a new active inventory adapter.
81    * @throws RestClientConstructionException 
82    *
83    */
84
85   public ActiveInventoryAdapter(OxmModelLoader oxmModelLoader, OxmEntityLookup oxmEntityLookup,
86       RestEndpointConfig endpointConfig)
87       throws ElasticSearchOperationException, IOException, RestClientConstructionException {
88
89     this.oxmModelLoader = oxmModelLoader;
90     this.oxmEntityLookup = oxmEntityLookup;
91     this.endpointConfig = endpointConfig;
92     
93     /*
94      * Add support for de-obfuscating basic auth password (if obfuscated)
95      */
96
97     if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
98       String basicAuthPassword = endpointConfig.getBasicAuthPassword();
99
100       if (basicAuthPassword != null
101           && basicAuthPassword.startsWith(SparkyConstants.OBFUSCATION_PREFIX)) {
102         Encryptor enc = new Encryptor();
103         endpointConfig.setBasicAuthPassword(enc.decryptValue(basicAuthPassword));
104       }
105     }
106
107     this.restClient = RestClientFactory.buildClient(endpointConfig);
108
109   }
110
111   protected Map<String, List<String>> getMessageHeaders() {
112
113     Map<String, List<String>> headers = new HashMap<String, List<String>>();
114
115     headers.putIfAbsent(HEADER_FROM_APP_ID, new ArrayList<String>());
116     headers.get(HEADER_FROM_APP_ID).add(UI_APP_NAME);
117
118     headers.putIfAbsent(HEADER_TRANS_ID, new ArrayList<String>());
119     headers.get(HEADER_TRANS_ID).add(TRANSACTION_ID_PREFIX + NodeUtils.getRandomTxnId());
120
121     if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
122       headers.putIfAbsent(HEADER_AUTHORIZATION, new ArrayList<String>());
123       headers.get(HEADER_AUTHORIZATION).add(getBasicAuthenticationCredentials());
124     }
125
126     return headers;
127   }
128
129   protected String getBasicAuthenticationCredentials() {
130
131     String usernameAndPassword = String.join(":", endpointConfig.getBasicAuthUserName(),
132         endpointConfig.getBasicAuthPassword());
133     return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes());
134   }
135
136   public OxmEntityLookup getOxmEntityLookup() {
137     return oxmEntityLookup;
138   }
139
140   public void setOxmEntityLookup(OxmEntityLookup oxmEntityLookup) {
141     this.oxmEntityLookup = oxmEntityLookup;
142   }
143
144   protected String getResourceBasePath() {
145
146     String versionStr = null;
147     if (oxmModelLoader != null) {
148       versionStr = String.valueOf(oxmModelLoader.getLatestVersionNum());
149     }
150
151     return "/aai/" + versionStr.toLowerCase();
152
153   }
154   
155   public static String extractResourcePath(String selflink) {
156     try {
157       return new URI(selflink).getRawPath();
158     } catch (URISyntaxException uriSyntaxException) {
159       LOG.error(AaiUiMsgs.ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK,
160           uriSyntaxException.getMessage());
161       return selflink;
162     }
163   }
164
165   
166   /**
167    * Gets the full url.
168    *
169    * @param resourceUrl the resource url
170    * @return the full url
171    * @throws Exception the exception
172    */
173   private String getFullUrl(String resourceUrl) throws Exception {
174     final String basePath = getResourceBasePath();
175     return String.format("https://%s:%s%s%s", endpointConfig.getEndpointIpAddress(),
176         endpointConfig.getEndpointServerPort(), basePath, resourceUrl);
177   }
178
179   public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams)
180       throws Exception {
181
182     URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query"));
183
184     for (String queryParam : queryParams) {
185       urlBuilder.addParameter("key", queryParam);
186     }
187
188     urlBuilder.addParameter("start-node-type", startNodeType);
189     urlBuilder.addParameter("include", startNodeType);
190
191     final String constructedLink = urlBuilder.toString();
192
193     return constructedLink;
194
195   }
196
197
198   public OperationResult getSelfLinksByEntityType(String entityType) throws Exception {
199
200     /*
201      * For this one, I want to dynamically construct the nodes-query for self-link discovery as a
202      * utility method that will use the OXM model entity data to drive the query as well.
203      */
204
205     if (entityType == null) {
206       throw new NullPointerException(
207           "Failed to getSelfLinksByEntityType() because entityType is null");
208     }
209
210     OxmEntityDescriptor entityDescriptor = oxmEntityLookup.getEntityDescriptors().get(entityType);
211
212     if (entityDescriptor == null) {
213       throw new NoSuchElementException("Failed to getSelfLinksByEntityType() because could"
214           + " not find entity descriptor from OXM with type = " + entityType);
215     }
216
217     String link = null;
218     final String primaryKeyStr =
219         NodeUtils.concatArray(entityDescriptor.getPrimaryKeyAttributeNames(), "/");
220
221     link = getFullUrl("/search/nodes-query?search-node-type=" + entityType + "&filter="
222         + primaryKeyStr + ":EXISTS");
223
224
225     return restClient.get(link, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
226
227   }
228
229   public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName,
230       String primaryKeyValue) throws Exception {
231
232     if (entityType == null) {
233       throw new NullPointerException("Failed to getSelfLinkForEntity() because entityType is null");
234     }
235
236     if (primaryKeyName == null) {
237       throw new NullPointerException(
238           "Failed to getSelfLinkForEntity() because primaryKeyName is null");
239     }
240
241     if (primaryKeyValue == null) {
242       throw new NullPointerException(
243           "Failed to getSelfLinkForEntity() because primaryKeyValue is null");
244     }
245
246     /*
247      * Try to protect ourselves from illegal URI formatting exceptions caused by characters that
248      * aren't natively supported in a URI, but can be escaped to make them legal.
249      */
250
251     String encodedEntityType = URLEncoder.encode(entityType, "UTF-8");
252     String encodedPrimaryKeyName = URLEncoder.encode(primaryKeyName, "UTF-8");
253     String encodedPrimaryKeyValue = URLEncoder.encode(primaryKeyValue, "UTF-8");
254
255     String link = null;
256
257     if ("service-instance".equals(entityType)) {
258
259       link = getFullUrl("/search/generic-query?key=" + encodedEntityType + "."
260           + encodedPrimaryKeyName + ":" + encodedPrimaryKeyValue + "&start-node-type="
261           + encodedEntityType + "&include=customer&depth=2");
262
263     } else {
264
265       link =
266           getFullUrl("/search/generic-query?key=" + encodedEntityType + "." + encodedPrimaryKeyName
267               + ":" + encodedPrimaryKeyValue + "&start-node-type=" + encodedEntityType);
268
269     }
270
271     return queryActiveInventoryWithRetries(link, "application/json",
272         endpointConfig.getNumRequestRetries());
273
274   }
275
276
277   /**
278    * Our retry conditions should be very specific.
279    *
280    * @param r the r
281    * @return true, if successful
282    */
283   private boolean shouldRetryRequest(OperationResult r) {
284
285     if (r == null) {
286       return true;
287     }
288
289     int rc = r.getResultCode();
290
291     if (rc == 200) {
292       return false;
293     }
294
295     if (rc == 404) {
296       return false;
297     }
298
299     return true;
300
301   }
302
303   /**
304    * Query active inventory.
305    *
306    * @param url the url
307    * @param acceptContentType the accept content type
308    * @return the operation result
309    */
310   // package protected for test classes instead of private
311   OperationResult queryActiveInventory(String url, String acceptContentType) {
312
313     return restClient.get(url, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
314
315   }
316
317   public RestEndpointConfig getEndpointConfig() {
318     return endpointConfig;
319   }
320
321   public void setEndpointConfig(RestEndpointConfig endpointConfig) {
322     this.endpointConfig = endpointConfig;
323   }
324
325   public OperationResult queryActiveInventoryWithRetries(String url, String responseType,
326       int numRetries) {
327
328     OperationResult result = null;
329
330     for (int retryCount = 0; retryCount < numRetries; retryCount++) {
331
332       LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_SEQ, url, String.valueOf(retryCount + 1));
333
334       result = queryActiveInventory(url, responseType);
335
336       /**
337        * Record number of times we have attempted the request to later summarize how many times we
338        * are generally retrying over thousands of messages in a sync.
339        * 
340        * If the number of retries is surprisingly high, then we need to understand why that is as
341        * the number of retries is also causing a heavier load on AAI beyond the throttling controls
342        * we already have in place in term of the transaction rate controller and number of
343        * parallelized threads per task processor.
344        */
345
346       result.setNumRetries(retryCount);
347
348       if (!shouldRetryRequest(result)) {
349
350         result.setFromCache(false);
351         LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_DONE_SEQ, url, String.valueOf(retryCount + 1));
352
353         return result;
354       }
355
356       try {
357         /*
358          * Sleep between re-tries to be nice to the target system.
359          */
360         Thread.sleep(50);
361       } catch (InterruptedException exc) {
362         LOG.error(AaiUiMsgs.QUERY_AAI_WAIT_INTERRUPTION, exc.getLocalizedMessage());
363         Thread.currentThread().interrupt();
364         break;
365       }
366       LOG.error(AaiUiMsgs.QUERY_AAI_RETRY_FAILURE_WITH_SEQ, url, String.valueOf(retryCount + 1));
367
368     }
369
370     LOG.info(AaiUiMsgs.QUERY_AAI_RETRY_MAXED_OUT, url);
371
372     return result;
373
374   }
375   
376   public String repairSelfLink(String selfLink) {
377     return repairSelfLink(selfLink, null);
378   }
379
380   /**
381    * This method adds a scheme, host and port (if missing) to the passed-in URI.
382    * If these parts of the URI are already present, they will not be duplicated.
383    * 
384    * @param selflink The URI to repair
385    * @param queryParams The query parameters as a single string
386    * @return The corrected URI (i.e. includes a scheme/host/port)
387    */
388   public String repairSelfLink(String selflink, String queryParams) {
389     if (selflink == null) {
390       return selflink;
391     }
392
393     UriBuilder builder = UriBuilder.fromPath(selflink).host(endpointConfig.getEndpointIpAddress())
394         .port(Integer.parseInt(endpointConfig.getEndpointServerPort()));
395
396     switch (endpointConfig.getRestAuthenticationMode()) {
397
398       case SSL_BASIC:
399       case SSL_CERT: {
400         builder.scheme(HTTPS_SCHEME);
401         break;
402       }
403
404       default: {
405         builder.scheme(HTTP_SCHEME);
406       }
407     }
408
409     boolean includeQueryParams = ( (null != queryParams) && (!"".equals(queryParams)) );
410
411     /* builder.build().toString() will encode special characters to hexadecimal pairs prefixed with a '%'
412        so we're adding the query parameters separately, in their UTF-8 representations, so that
413        characters such as '?', '&', etc. remain intact as needed by the synchronizer */
414     return (builder.build().toString() + (includeQueryParams ? queryParams : ""));
415   }
416
417 }