2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sparky.synchronizer;
25 import static java.util.concurrent.CompletableFuture.supplyAsync;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Deque;
32 import java.util.EnumSet;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.concurrent.ConcurrentHashMap;
38 import java.util.concurrent.ConcurrentLinkedDeque;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.atomic.AtomicInteger;
41 import java.util.function.Supplier;
43 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
44 import org.onap.aai.sparky.dal.NetworkTransaction;
45 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig;
46 import org.onap.aai.sparky.dal.rest.HttpMethod;
47 import org.onap.aai.sparky.dal.rest.OperationResult;
48 import org.onap.aai.sparky.logging.AaiUiMsgs;
49 import org.onap.aai.sparky.synchronizer.config.SynchronizerConfiguration;
50 import org.onap.aai.sparky.synchronizer.entity.SelfLinkDescriptor;
51 import org.onap.aai.sparky.synchronizer.entity.SuggestionSearchEntity;
52 import org.onap.aai.sparky.synchronizer.enumeration.OperationState;
53 import org.onap.aai.sparky.synchronizer.enumeration.SynchronizerState;
54 import org.onap.aai.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
55 import org.onap.aai.sparky.synchronizer.task.PerformElasticSearchPut;
56 import org.onap.aai.sparky.synchronizer.task.PerformElasticSearchRetrieval;
57 import org.onap.aai.sparky.util.NodeUtils;
58 import org.onap.aai.sparky.util.SuggestionsPermutation;
59 import org.onap.aai.cl.api.Logger;
60 import org.onap.aai.cl.eelf.LoggerFactory;
61 import org.onap.aai.cl.mdc.MdcContext;
64 import com.fasterxml.jackson.core.JsonProcessingException;
65 import com.fasterxml.jackson.databind.JsonNode;
66 import com.fasterxml.jackson.databind.node.ArrayNode;
69 * The Class AutosuggestionSynchronizer.
71 public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer
72 implements IndexSynchronizer {
74 private class RetrySuggestionEntitySyncContainer {
75 NetworkTransaction txn;
76 SuggestionSearchEntity ssec;
79 * Instantiates a new RetrySuggestionEntitySyncContainer.
82 * @param icer the icer
84 public RetrySuggestionEntitySyncContainer(NetworkTransaction txn, SuggestionSearchEntity icer) {
89 public NetworkTransaction getNetworkTransaction() {
93 public SuggestionSearchEntity getSuggestionSearchEntity() {
98 private static final Logger LOG =
99 LoggerFactory.getInstance().getLogger(AutosuggestionSynchronizer.class);
100 private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
102 private boolean allWorkEnumerated;
103 private Deque<SelfLinkDescriptor> selflinks;
104 private ConcurrentHashMap<String, AtomicInteger> entityCounters;
105 private boolean syncInProgress;
106 private Map<String, String> contextMap;
107 protected ExecutorService esPutExecutor;
108 private Deque<RetrySuggestionEntitySyncContainer> retryQueue;
109 private Map<String, Integer> retryLimitTracker;
112 * Instantiates a new historical entity summarizer.
114 * @param indexName the index name
115 * @throws Exception the exception
117 public AutosuggestionSynchronizer(String indexName) throws Exception {
118 super(LOG, "ASES-" + indexName.toUpperCase(), 2, 5, 5, indexName); // multiple Autosuggestion
119 // Entity Synchronizer will
120 // run for different indices
122 this.allWorkEnumerated = false;
123 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
124 this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
125 this.synchronizerName = "Autosuggestion Entity Synchronizer";
126 this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
127 this.syncInProgress = false;
128 this.contextMap = MDC.getCopyOfContextMap();
129 this.esPutExecutor = NodeUtils.createNamedExecutor("SUES-ES-PUT", 5, LOG);
130 this.syncDurationInMs = -1;
134 * Collect all the work.
136 * @return the operation state
138 private OperationState collectAllTheWork() {
139 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
140 Map<String, OxmEntityDescriptor> descriptorMap =
141 oxmModelLoader.getSuggestionSearchEntityDescriptors();
143 if (descriptorMap.isEmpty()) {
144 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
145 LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
146 return OperationState.ERROR;
149 Collection<String> syncTypes = descriptorMap.keySet();
154 * launch a parallel async thread to process the documents for each entity-type (to max the of
155 * the configured executor anyway)
158 aaiWorkOnHand.set(syncTypes.size());
160 for (String key : syncTypes) {
162 supplyAsync(new Supplier<Void>() {
166 MDC.setContextMap(contextMap);
167 OperationResult typeLinksResult = null;
169 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
170 aaiWorkOnHand.decrementAndGet();
171 processEntityTypeSelfLinks(typeLinksResult);
172 } catch (Exception exc) {
173 // TODO -> LOG, what should be logged here?
179 }, aaiExecutor).whenComplete((result, error) -> {
182 LOG.error(AaiUiMsgs.ERROR_GENERIC,
183 "An error occurred getting data from AAI. Error = " + error.getMessage());
189 while (aaiWorkOnHand.get() != 0) {
191 if (LOG.isDebugEnabled()) {
192 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
198 aaiWorkOnHand.set(selflinks.size());
199 allWorkEnumerated = true;
202 while (!isSyncDone()) {
208 * Make sure we don't hang on to retries that failed which could cause issues during future
211 retryLimitTracker.clear();
213 } catch (Exception exc) {
214 // TODO -> LOG, waht should be logged here?
217 return OperationState.OK;
224 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync()
227 public OperationState doSync() {
228 this.syncDurationInMs = -1;
229 syncStartedTimeStampInMs = System.currentTimeMillis();
230 String txnID = NodeUtils.getRandomTxnId();
231 MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", "");
233 return collectAllTheWork();
237 * Process entity type self links.
239 * @param operationResult the operation result
241 private void processEntityTypeSelfLinks(OperationResult operationResult) {
243 JsonNode rootNode = null;
245 final String jsonResult = operationResult.getResult();
247 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
250 rootNode = mapper.readTree(jsonResult);
251 } catch (IOException exc) {
252 String message = "Could not deserialize JSON (representing operation result) as node tree. "
253 + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
254 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
258 JsonNode resultData = rootNode.get("result-data");
259 ArrayNode resultDataArrayNode = null;
261 if (resultData.isArray()) {
262 resultDataArrayNode = (ArrayNode) resultData;
264 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
265 JsonNode element = null;
267 while (elementIterator.hasNext()) {
268 element = elementIterator.next();
270 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
271 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
273 OxmEntityDescriptor descriptor = null;
275 if (resourceType != null && resourceLink != null) {
277 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
279 if (descriptor == null) {
280 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
281 // go to next element in iterator
284 selflinks.add(new SelfLinkDescriptor(resourceLink,
285 SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType));
297 private void syncEntityTypes() {
299 while (selflinks.peek() != null) {
301 SelfLinkDescriptor linkDescriptor = selflinks.poll();
302 aaiWorkOnHand.decrementAndGet();
304 OxmEntityDescriptor descriptor = null;
306 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
308 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
310 if (descriptor == null) {
311 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
312 // go to next element in iterator
316 NetworkTransaction txn = new NetworkTransaction();
317 txn.setDescriptor(descriptor);
318 txn.setLink(linkDescriptor.getSelfLink());
319 txn.setOperationType(HttpMethod.GET);
320 txn.setEntityType(linkDescriptor.getEntityType());
322 aaiWorkOnHand.incrementAndGet();
324 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
325 .whenComplete((result, error) -> {
327 aaiWorkOnHand.decrementAndGet();
330 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
332 if (result == null) {
333 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
334 linkDescriptor.getSelfLink());
336 updateActiveInventoryCounters(result);
337 fetchDocumentForUpsert(result);
348 * Return a set of valid suggestion attributes for the provided entityName that are present in the
351 * @param node JSON node in which the attributes should be found
353 * @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 sse.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink()));
404 populateSuggestionSearchEntityDocument(sse, jsonResult, txn);
405 // The unique id for the document will be created at derive fields
407 // Insert the document only if it has valid statuses
408 if (sse.isSuggestableDoc()) {
411 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
412 } catch (Exception exc) {
413 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
417 NetworkTransaction n2 = new NetworkTransaction();
419 n2.setEntityType(txn.getEntityType());
420 n2.setDescriptor(txn.getDescriptor());
421 n2.setOperationType(HttpMethod.GET);
423 esWorkOnHand.incrementAndGet();
425 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor)
426 .whenComplete((result, error) -> {
428 esWorkOnHand.decrementAndGet();
431 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
433 updateElasticSearchCounters(result);
434 performDocumentUpsert(result, sse);
441 } catch (JsonProcessingException exc) {
442 // TODO -> LOG, waht should be logged here?
443 } catch (IOException exc) {
444 // TODO -> LOG, waht should be logged here?
448 protected void populateSuggestionSearchEntityDocument(SuggestionSearchEntity sse, String result,
449 NetworkTransaction txn) throws JsonProcessingException, IOException {
451 OxmEntityDescriptor resultDescriptor = txn.getDescriptor();
453 sse.setEntityType(resultDescriptor.getEntityName());
455 JsonNode entityNode = mapper.readTree(result);
457 List<String> primaryKeyValues = new ArrayList<String>();
458 String pkeyValue = null;
460 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
461 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
462 if (pkeyValue != null) {
463 primaryKeyValues.add(pkeyValue);
465 String message = "populateSuggestionSearchEntityDocument(),"
466 + " pKeyValue is null for entityType = " + resultDescriptor.getEntityName();
467 LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
471 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
472 sse.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
473 sse.generateSuggestionInputPermutations();
476 protected void performDocumentUpsert(NetworkTransaction esGetTxn, SuggestionSearchEntity sse) {
480 * As part of the response processing we need to do the following:
481 * <li>1. Extract the version (if present), it will be the ETAG when we use the
482 * Search-Abstraction-Service
483 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
485 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
486 * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
492 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
493 } catch (Exception exc) {
494 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
498 boolean wasEntryDiscovered = false;
499 if (esGetTxn.getOperationResult().getResultCode() == 404) {
500 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, sse.getEntityPrimaryKeyValue());
501 } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
502 wasEntryDiscovered = true;
505 * Not being a 200 does not mean a failure. eg 201 is returned for created. and 500 for es not
506 * found TODO -> Should we return.
508 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
509 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
512 // Insert a new document only if the paylod is different.
513 // This is determined by hashing the payload and using it as a id for the document
515 if (!wasEntryDiscovered) {
517 String jsonPayload = null;
519 jsonPayload = sse.getIndexDocumentJson();
520 if (link != null && jsonPayload != null) {
522 NetworkTransaction updateElasticTxn = new NetworkTransaction();
523 updateElasticTxn.setLink(link);
524 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
525 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
526 updateElasticTxn.setOperationType(HttpMethod.PUT);
528 esWorkOnHand.incrementAndGet();
529 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
530 esPutExecutor).whenComplete((result, error) -> {
532 esWorkOnHand.decrementAndGet();
535 String message = "Suggestion search entity sync UPDATE PUT error - "
536 + error.getLocalizedMessage();
537 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
539 updateElasticSearchCounters(result);
540 processStoreDocumentResult(result, esGetTxn, sse);
544 } catch (Exception exc) {
546 "Exception caught during suggestion search entity sync PUT operation. Message - "
547 + exc.getLocalizedMessage();
548 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
553 private void processStoreDocumentResult(NetworkTransaction esPutResult,
554 NetworkTransaction esGetResult, SuggestionSearchEntity sse) {
556 OperationResult or = esPutResult.getOperationResult();
558 if (!or.wasSuccessful()) {
559 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
561 if (shouldAllowRetry(sse.getId())) {
562 esWorkOnHand.incrementAndGet();
564 RetrySuggestionEntitySyncContainer rssec =
565 new RetrySuggestionEntitySyncContainer(esGetResult, sse);
566 retryQueue.push(rssec);
568 String message = "Store document failed during suggestion search entity synchronization"
569 + " due to version conflict. Entity will be re-synced.";
570 LOG.warn(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
574 "Store document failed during suggestion search entity synchronization with result code "
575 + or.getResultCode() + " and result message " + or.getResult();
576 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
582 * Perform retry sync.
584 private void performRetrySync() {
585 while (retryQueue.peek() != null) {
587 RetrySuggestionEntitySyncContainer susc = retryQueue.poll();
590 SuggestionSearchEntity sus = susc.getSuggestionSearchEntity();
591 NetworkTransaction txn = susc.getNetworkTransaction();
596 * In this retry flow the se object has already derived its fields
598 link = getElasticFullUrl("/" + sus.getId(), getIndexName());
599 } catch (Exception exc) {
600 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
604 NetworkTransaction retryTransaction = new NetworkTransaction();
605 retryTransaction.setLink(link);
606 retryTransaction.setEntityType(txn.getEntityType());
607 retryTransaction.setDescriptor(txn.getDescriptor());
608 retryTransaction.setOperationType(HttpMethod.GET);
611 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
612 * called incrementAndGet when queuing the failed PUT!
615 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
616 esExecutor).whenComplete((result, error) -> {
618 esWorkOnHand.decrementAndGet();
621 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
623 updateElasticSearchCounters(result);
624 performDocumentUpsert(result, sus);
634 * Should allow retry.
637 * @return true, if successful
639 private boolean shouldAllowRetry(String id) {
640 boolean isRetryAllowed = true;
641 if (retryLimitTracker.get(id) != null) {
642 Integer currentCount = retryLimitTracker.get(id);
643 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
644 isRetryAllowed = false;
645 String message = "Searchable entity re-sync limit reached for " + id
646 + ", re-sync will no longer be attempted for this entity";
647 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
649 Integer newCount = new Integer(currentCount.intValue() + 1);
650 retryLimitTracker.put(id, newCount);
653 Integer firstRetryCount = new Integer(1);
654 retryLimitTracker.put(id, firstRetryCount);
657 return isRetryAllowed;
663 public SynchronizerState getState() {
666 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
669 return SynchronizerState.IDLE;
676 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
679 public String getStatReport(boolean showFinalReport) {
680 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
681 return getStatReport(syncDurationInMs, showFinalReport);
687 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown()
690 public void shutdown() {
691 this.shutdownExecutors();
695 protected boolean isSyncDone() {
697 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
699 if (LOG.isDebugEnabled()) {
700 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
701 + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
704 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
708 this.syncInProgress = false;
716 * @see org.onap.aai.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
719 public void clearCache() {
721 if (syncInProgress) {
722 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
723 "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
728 this.resetCounters();
729 if (entityCounters != null) {
730 entityCounters.clear();
733 allWorkEnumerated = false;