2 * ============LICENSE_START===================================================
3 * SPARKY (AAI UI service)
4 * ============================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=====================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
26 package org.openecomp.sparky.synchronizer;
28 import static java.util.concurrent.CompletableFuture.supplyAsync;
30 import java.io.IOException;
31 import java.net.InetAddress;
32 import java.net.UnknownHostException;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Collection;
36 import java.util.Deque;
37 import java.util.EnumSet;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.List;
42 import java.util.concurrent.ConcurrentHashMap;
43 import java.util.concurrent.ConcurrentLinkedDeque;
44 import java.util.concurrent.ExecutorService;
45 import java.util.concurrent.atomic.AtomicInteger;
46 import java.util.function.Supplier;
48 import org.openecomp.cl.api.Logger;
49 import org.openecomp.cl.eelf.LoggerFactory;
50 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
51 import org.openecomp.sparky.dal.NetworkTransaction;
52 import org.openecomp.sparky.dal.rest.HttpMethod;
53 import org.openecomp.sparky.dal.rest.OperationResult;
54 import org.openecomp.sparky.logging.AaiUiMsgs;
55 import org.openecomp.sparky.synchronizer.config.SynchronizerConfiguration;
56 import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
57 import org.openecomp.sparky.synchronizer.entity.SuggestionSearchEntity;
58 import org.openecomp.sparky.synchronizer.enumeration.OperationState;
59 import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState;
60 import org.openecomp.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
61 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchPut;
62 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchRetrieval;
63 import org.openecomp.sparky.util.NodeUtils;
64 import org.openecomp.sparky.util.SuggestionsPermutation;
67 import org.openecomp.cl.mdc.MdcContext;
69 import org.openecomp.cl.mdc.MdcContext;
71 import org.openecomp.cl.mdc.MdcContext;
72 import com.fasterxml.jackson.core.JsonProcessingException;
73 import com.fasterxml.jackson.databind.JsonNode;
74 import com.fasterxml.jackson.databind.node.ArrayNode;
77 * The Class AutosuggestionSynchronizer.
79 public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer
80 implements IndexSynchronizer {
82 private class RetrySuggestionEntitySyncContainer {
83 NetworkTransaction txn;
84 SuggestionSearchEntity ssec;
87 * Instantiates a new RetrySuggestionEntitySyncContainer.
90 * @param icer the icer
92 public RetrySuggestionEntitySyncContainer(NetworkTransaction txn, SuggestionSearchEntity icer) {
97 public NetworkTransaction getNetworkTransaction() {
101 public SuggestionSearchEntity getSuggestionSearchEntity() {
106 private static final Logger LOG =
107 LoggerFactory.getInstance().getLogger(AutosuggestionSynchronizer.class);
108 private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
110 private boolean allWorkEnumerated;
111 private Deque<SelfLinkDescriptor> selflinks;
112 private ConcurrentHashMap<String, AtomicInteger> entityCounters;
113 private boolean syncInProgress;
114 private Map<String, String> contextMap;
115 protected ExecutorService esPutExecutor;
116 private Deque<RetrySuggestionEntitySyncContainer> retryQueue;
117 private Map<String, Integer> retryLimitTracker;
120 * Instantiates a new historical entity summarizer.
122 * @param indexName the index name
123 * @throws Exception the exception
125 public AutosuggestionSynchronizer(String indexName) throws Exception {
126 super(LOG, "ASES-" + indexName.toUpperCase(), 2, 5, 5, indexName); // multiple Autosuggestion
127 // Entity Synchronizer will
128 // run for different indices
130 this.allWorkEnumerated = false;
131 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
132 this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
133 this.synchronizerName = "Autosuggestion Entity Synchronizer";
134 this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
135 this.syncInProgress = false;
136 this.contextMap = MDC.getCopyOfContextMap();
137 this.esPutExecutor = NodeUtils.createNamedExecutor("SUES-ES-PUT", 5, LOG);
141 * Collect all the work.
143 * @return the operation state
145 private OperationState collectAllTheWork() {
146 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
147 Map<String, OxmEntityDescriptor> descriptorMap =
148 oxmModelLoader.getSuggestionSearchEntityDescriptors();
150 if (descriptorMap.isEmpty()) {
151 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
152 LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
153 return OperationState.ERROR;
156 Collection<String> syncTypes = descriptorMap.keySet();
161 * launch a parallel async thread to process the documents for each entity-type (to max the of
162 * the configured executor anyway)
165 aaiWorkOnHand.set(syncTypes.size());
167 for (String key : syncTypes) {
169 supplyAsync(new Supplier<Void>() {
173 MDC.setContextMap(contextMap);
174 OperationResult typeLinksResult = null;
176 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
177 aaiWorkOnHand.decrementAndGet();
178 processEntityTypeSelfLinks(typeLinksResult);
179 } catch (Exception exc) {
180 // TODO -> LOG, what should be logged here?
186 }, aaiExecutor).whenComplete((result, error) -> {
189 LOG.error(AaiUiMsgs.ERROR_GENERIC,
190 "An error occurred getting data from AAI. Error = " + error.getMessage());
196 while (aaiWorkOnHand.get() != 0) {
198 if (LOG.isDebugEnabled()) {
199 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
205 aaiWorkOnHand.set(selflinks.size());
206 allWorkEnumerated = true;
209 while (!isSyncDone()) {
215 * Make sure we don't hang on to retries that failed which could cause issues during future
218 retryLimitTracker.clear();
220 } catch (Exception exc) {
221 // TODO -> LOG, waht should be logged here?
224 return OperationState.OK;
231 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
234 public OperationState doSync() {
235 String txnID = NodeUtils.getRandomTxnId();
236 MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", "");
238 return collectAllTheWork();
242 * Process entity type self links.
244 * @param operationResult the operation result
246 private void processEntityTypeSelfLinks(OperationResult operationResult) {
248 JsonNode rootNode = null;
250 final String jsonResult = operationResult.getResult();
252 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
255 rootNode = mapper.readTree(jsonResult);
256 } catch (IOException exc) {
257 String message = "Could not deserialize JSON (representing operation result) as node tree. "
258 + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
259 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
262 JsonNode resultData = rootNode.get("result-data");
263 ArrayNode resultDataArrayNode = null;
265 if (resultData.isArray()) {
266 resultDataArrayNode = (ArrayNode) resultData;
268 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
269 JsonNode element = null;
271 while (elementIterator.hasNext()) {
272 element = elementIterator.next();
274 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
275 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
277 OxmEntityDescriptor descriptor = null;
279 if (resourceType != null && resourceLink != null) {
281 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
283 if (descriptor == null) {
284 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
285 // go to next element in iterator
288 selflinks.add(new SelfLinkDescriptor(resourceLink,
289 SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType));
301 private void syncEntityTypes() {
303 while (selflinks.peek() != null) {
305 SelfLinkDescriptor linkDescriptor = selflinks.poll();
306 aaiWorkOnHand.decrementAndGet();
308 OxmEntityDescriptor descriptor = null;
310 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
312 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
314 if (descriptor == null) {
315 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
316 // go to next element in iterator
320 NetworkTransaction txn = new NetworkTransaction();
321 txn.setDescriptor(descriptor);
322 txn.setLink(linkDescriptor.getSelfLink());
323 txn.setOperationType(HttpMethod.GET);
324 txn.setEntityType(linkDescriptor.getEntityType());
326 aaiWorkOnHand.incrementAndGet();
328 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
329 .whenComplete((result, error) -> {
331 aaiWorkOnHand.decrementAndGet();
334 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
336 if (result == null) {
337 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
338 linkDescriptor.getSelfLink());
340 updateActiveInventoryCounters(result);
341 fetchDocumentForUpsert(result);
351 * Return a set of valid suggestion attributes for the provided entityName
352 * that are present in the JSON
353 * @param node JSON node in which the attributes should be found
354 * @param entityName Name of the entity
355 * @return List of all valid suggestion attributes(key's)
357 public List<String> getSuggestionFromReponse(JsonNode node, String entityName) {
358 List<String> suggestableAttr = new ArrayList<String>();
359 HashMap<String, String> desc = oxmModelLoader.getOxmModel().get(entityName);
360 String attr = desc.get("suggestibleAttributes");
361 suggestableAttr = Arrays.asList(attr.split(","));
362 List<String> suggestableValue = new ArrayList<>();
363 for (String attribute : suggestableAttr) {
364 if (node.get(attribute) != null && node.get(attribute).asText().length() > 0) {
365 suggestableValue.add(attribute);
368 return suggestableValue;
372 * Fetch all the documents for upsert. Based on the number of permutations that are available the
373 * number of documents will be different
377 private void fetchDocumentForUpsert(NetworkTransaction txn) {
378 if (!txn.getOperationResult().wasSuccessful()) {
379 String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
380 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
384 final String jsonResult = txn.getOperationResult().getResult();
386 if (jsonResult != null && jsonResult.length() > 0) {
388 // Step 1: Calculate the number of possible permutations of attributes
389 String entityName = txn.getDescriptor().getEntityName();
390 JsonNode entityNode = mapper.readTree(jsonResult);
392 SuggestionsPermutation suggPermutation = new SuggestionsPermutation();
393 ArrayList<ArrayList<String>> uniqueLists = suggPermutation
394 .getSuggestionsPermutation(getSuggestionFromReponse(entityNode, entityName));
396 // Now we have a list of all possible permutations for the status that are
397 // defined for this entity type. Try inserting a document for every combination.
398 for (ArrayList<String> uniqueList : uniqueLists) {
399 SuggestionSearchEntity sse = new SuggestionSearchEntity(oxmModelLoader);
400 sse.setSuggestableAttr(uniqueList);
401 sse.setPayloadFromResponse(entityNode);
402 sse.setLink(txn.getLink());
403 populateSuggestionSearchEntityDocument(sse, jsonResult, txn);
404 // The unique id for the document will be created at derive fields
406 // Insert the document only if it has valid statuses
407 if (sse.isSuggestableDoc()) {
410 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
411 } catch (Exception exc) {
412 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
416 NetworkTransaction n2 = new NetworkTransaction();
418 n2.setEntityType(txn.getEntityType());
419 n2.setDescriptor(txn.getDescriptor());
420 n2.setOperationType(HttpMethod.GET);
422 esWorkOnHand.incrementAndGet();
424 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor)
425 .whenComplete((result, error) -> {
427 esWorkOnHand.decrementAndGet();
430 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
432 updateElasticSearchCounters(result);
433 performDocumentUpsert(result, sse);
440 } catch (JsonProcessingException exc) {
441 // TODO -> LOG, waht should be logged here?
442 } catch (IOException exc) {
443 // TODO -> LOG, waht should be logged here?
447 protected void populateSuggestionSearchEntityDocument(SuggestionSearchEntity sse, String result,
448 NetworkTransaction txn) throws JsonProcessingException, IOException {
450 OxmEntityDescriptor resultDescriptor = txn.getDescriptor();
452 sse.setEntityType(resultDescriptor.getEntityName());
454 JsonNode entityNode = mapper.readTree(result);
456 List<String> primaryKeyValues = new ArrayList<String>();
457 String pkeyValue = null;
459 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
460 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
461 if (pkeyValue != null) {
462 primaryKeyValues.add(pkeyValue);
464 String message = "populateSuggestionSearchEntityDocument(),"
465 + " pKeyValue is null for entityType = " + resultDescriptor.getEntityName();
466 LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
470 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
471 sse.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
472 sse.generateSuggestionInputPermutations();
475 protected void performDocumentUpsert(NetworkTransaction esGetTxn, SuggestionSearchEntity sse) {
479 * As part of the response processing we need to do the following:
480 * <li>1. Extract the version (if present), it will be the ETAG when we use the
481 * Search-Abstraction-Service
482 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
484 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
485 * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
491 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
492 } catch (Exception exc) {
493 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
497 boolean wasEntryDiscovered = false;
498 if (esGetTxn.getOperationResult().getResultCode() == 404) {
499 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, sse.getEntityPrimaryKeyValue());
500 } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
501 wasEntryDiscovered = true;
504 * Not being a 200 does not mean a failure. eg 201 is returned for created. and 500 for es not
505 * found TODO -> Should we return.
507 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
508 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
511 // Insert a new document only if the paylod is different.
512 // This is determined by hashing the payload and using it as a id for the document
514 if (!wasEntryDiscovered) {
516 String jsonPayload = null;
518 jsonPayload = sse.getIndexDocumentJson();
519 if (link != null && jsonPayload != null) {
521 NetworkTransaction updateElasticTxn = new NetworkTransaction();
522 updateElasticTxn.setLink(link);
523 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
524 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
525 updateElasticTxn.setOperationType(HttpMethod.PUT);
527 esWorkOnHand.incrementAndGet();
528 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
529 esPutExecutor).whenComplete((result, error) -> {
531 esWorkOnHand.decrementAndGet();
534 String message = "Suggestion search entity sync UPDATE PUT error - "
535 + error.getLocalizedMessage();
536 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
538 updateElasticSearchCounters(result);
539 processStoreDocumentResult(result, esGetTxn, sse);
543 } catch (Exception exc) {
545 "Exception caught during suggestion search entity sync PUT operation. Message - "
546 + exc.getLocalizedMessage();
547 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
552 private void processStoreDocumentResult(NetworkTransaction esPutResult,
553 NetworkTransaction esGetResult, SuggestionSearchEntity sse) {
555 OperationResult or = esPutResult.getOperationResult();
557 if (!or.wasSuccessful()) {
558 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
560 if (shouldAllowRetry(sse.getId())) {
561 esWorkOnHand.incrementAndGet();
563 RetrySuggestionEntitySyncContainer rssec =
564 new RetrySuggestionEntitySyncContainer(esGetResult, sse);
565 retryQueue.push(rssec);
567 String message = "Store document failed during suggestion search entity synchronization"
568 + " due to version conflict. Entity will be re-synced.";
569 LOG.warn(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
573 "Store document failed during suggestion search entity synchronization with result code "
574 + or.getResultCode() + " and result message " + or.getResult();
575 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
581 * Perform retry sync.
583 private void performRetrySync() {
584 while (retryQueue.peek() != null) {
586 RetrySuggestionEntitySyncContainer susc = retryQueue.poll();
589 SuggestionSearchEntity sus = susc.getSuggestionSearchEntity();
590 NetworkTransaction txn = susc.getNetworkTransaction();
595 * In this retry flow the se object has already derived its fields
597 link = getElasticFullUrl("/" + sus.getId(), getIndexName());
598 } catch (Exception exc) {
599 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
603 NetworkTransaction retryTransaction = new NetworkTransaction();
604 retryTransaction.setLink(link);
605 retryTransaction.setEntityType(txn.getEntityType());
606 retryTransaction.setDescriptor(txn.getDescriptor());
607 retryTransaction.setOperationType(HttpMethod.GET);
610 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
611 * called incrementAndGet when queuing the failed PUT!
614 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
615 esExecutor).whenComplete((result, error) -> {
617 esWorkOnHand.decrementAndGet();
620 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
622 updateElasticSearchCounters(result);
623 performDocumentUpsert(result, sus);
633 * Should allow retry.
636 * @return true, if successful
638 private boolean shouldAllowRetry(String id) {
639 boolean isRetryAllowed = true;
640 if (retryLimitTracker.get(id) != null) {
641 Integer currentCount = retryLimitTracker.get(id);
642 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
643 isRetryAllowed = false;
644 String message = "Searchable entity re-sync limit reached for " + id
645 + ", re-sync will no longer be attempted for this entity";
646 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
648 Integer newCount = new Integer(currentCount.intValue() + 1);
649 retryLimitTracker.put(id, newCount);
652 Integer firstRetryCount = new Integer(1);
653 retryLimitTracker.put(id, firstRetryCount);
656 return isRetryAllowed;
662 public SynchronizerState getState() {
665 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
668 return SynchronizerState.IDLE;
675 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
678 public String getStatReport(boolean showFinalReport) {
679 return getStatReport(System.currentTimeMillis() - this.syncStartedTimeStampInMs,
686 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
689 public void shutdown() {
690 this.shutdownExecutors();
694 protected boolean isSyncDone() {
696 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
698 if (LOG.isDebugEnabled()) {
699 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
700 + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
703 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
707 this.syncInProgress = false;
715 * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
718 public void clearCache() {
720 if (syncInProgress) {
721 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
722 "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
727 this.resetCounters();
728 if (entityCounters != null) {
729 entityCounters.clear();
732 allWorkEnumerated = false;