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.net.InetAddress;
29 import java.net.UnknownHostException;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Deque;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.ConcurrentLinkedDeque;
38 import java.util.concurrent.ExecutorService;
39 import java.util.function.Supplier;
41 import org.onap.aai.sparky.config.oxm.CrossEntityReference;
42 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
43 import org.onap.aai.sparky.dal.NetworkTransaction;
44 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig;
45 import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
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.IndexableCrossEntityReference;
51 import org.onap.aai.sparky.synchronizer.entity.MergableEntity;
52 import org.onap.aai.sparky.synchronizer.entity.SelfLinkDescriptor;
53 import org.onap.aai.sparky.synchronizer.enumeration.OperationState;
54 import org.onap.aai.sparky.synchronizer.enumeration.SynchronizerState;
55 import org.onap.aai.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
56 import org.onap.aai.sparky.synchronizer.task.PerformElasticSearchPut;
57 import org.onap.aai.sparky.synchronizer.task.PerformElasticSearchRetrieval;
58 import org.onap.aai.sparky.synchronizer.task.PerformElasticSearchUpdate;
59 import org.onap.aai.sparky.util.NodeUtils;
60 import org.onap.aai.cl.api.Logger;
61 import org.onap.aai.cl.eelf.LoggerFactory;
64 import org.onap.aai.cl.mdc.MdcContext;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.JsonNode;
67 import com.fasterxml.jackson.databind.ObjectReader;
68 import com.fasterxml.jackson.databind.node.ArrayNode;
71 * The Class CrossEntityReferenceSynchronizer.
73 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
74 implements IndexSynchronizer {
77 * The Class RetryCrossEntitySyncContainer.
79 private class RetryCrossEntitySyncContainer {
80 NetworkTransaction txn;
81 IndexableCrossEntityReference icer;
84 * Instantiates a new retry cross entity sync container.
87 * @param icer the icer
89 public RetryCrossEntitySyncContainer(NetworkTransaction txn,
90 IndexableCrossEntityReference icer) {
95 public NetworkTransaction getNetworkTransaction() {
99 public IndexableCrossEntityReference getIndexableCrossEntityReference() {
104 private static final Logger LOG =
105 LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
107 private static final String SERVICE_INSTANCE = "service-instance";
108 private Deque<SelfLinkDescriptor> selflinks;
109 private Deque<RetryCrossEntitySyncContainer> retryQueue;
110 private Map<String, Integer> retryLimitTracker;
111 private boolean isAllWorkEnumerated;
112 protected ExecutorService esPutExecutor;
113 protected ActiveInventoryConfig aaiConfig;
116 * Instantiates a new cross entity reference synchronizer.
118 * @param indexName the index name
119 * @throws Exception the exception
121 public CrossEntityReferenceSynchronizer(String indexName, ActiveInventoryConfig aaiConfig)
123 super(LOG, "CERS", 2, 5, 5, indexName);
124 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
125 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
126 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
127 this.synchronizerName = "Cross Reference Entity Synchronizer";
128 this.isAllWorkEnumerated = false;
129 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
130 this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(
131 oxmModelLoader.getCrossReferenceEntityDescriptors());
132 this.esEntityStats.initializeCountersFromOxmEntityDescriptors(
133 oxmModelLoader.getCrossReferenceEntityDescriptors());
134 this.aaiConfig = aaiConfig;
135 this.syncDurationInMs = -1;
141 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync()
144 public OperationState doSync() {
145 this.syncDurationInMs = -1;
146 String txnID = NodeUtils.getRandomTxnId();
147 MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
150 syncStartedTimeStampInMs = System.currentTimeMillis();
152 return OperationState.OK;
156 public SynchronizerState getState() {
158 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
161 return SynchronizerState.IDLE;
167 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
170 public String getStatReport(boolean showFinalReport) {
171 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
172 return getStatReport(syncDurationInMs, showFinalReport);
178 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown()
181 public void shutdown() {
182 this.shutdownExecutors();
186 protected boolean isSyncDone() {
187 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
189 if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
199 * @return the operation state
201 private OperationState launchSyncFlow() {
202 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
203 Map<String, OxmEntityDescriptor> descriptorMap =
204 oxmModelLoader.getCrossReferenceEntityDescriptors();
206 if (descriptorMap.isEmpty()) {
207 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
209 return OperationState.ERROR;
212 Collection<String> syncTypes = descriptorMap.keySet();
217 * launch a parallel async thread to process the documents for each entity-type (to max the of
218 * the configured executor anyway)
221 aaiWorkOnHand.set(syncTypes.size());
223 for (String key : syncTypes) {
225 supplyAsync(new Supplier<Void>() {
229 MDC.setContextMap(contextMap);
230 OperationResult typeLinksResult = null;
232 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
233 aaiWorkOnHand.decrementAndGet();
234 processEntityTypeSelfLinks(typeLinksResult);
235 } catch (Exception exc) {
236 // TODO -> LOG, what should be logged here?
242 }, aaiExecutor).whenComplete((result, error) -> {
244 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
249 while (aaiWorkOnHand.get() != 0) {
251 if (LOG.isDebugEnabled()) {
252 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
258 aaiWorkOnHand.set(selflinks.size());
259 isAllWorkEnumerated = true;
262 while (!isSyncDone()) {
268 * Make sure we don't hang on to retries that failed which could cause issues during future
271 retryLimitTracker.clear();
273 } catch (Exception exc) {
274 // TODO -> LOG, waht should be logged here?
277 return OperationState.OK;
283 private void performSync() {
284 while (selflinks.peek() != null) {
286 SelfLinkDescriptor linkDescriptor = selflinks.poll();
287 aaiWorkOnHand.decrementAndGet();
289 OxmEntityDescriptor descriptor = null;
291 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
293 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
295 if (descriptor == null) {
296 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
297 // go to next element in iterator
301 if (descriptor.hasCrossEntityReferences()) {
303 NetworkTransaction txn = new NetworkTransaction();
304 txn.setDescriptor(descriptor);
305 txn.setLink(linkDescriptor.getSelfLink() + linkDescriptor.getDepthModifier());
306 txn.setOperationType(HttpMethod.GET);
307 txn.setEntityType(linkDescriptor.getEntityType());
309 aaiWorkOnHand.incrementAndGet();
311 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
312 .whenComplete((result, error) -> {
314 aaiWorkOnHand.decrementAndGet();
317 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
319 if (result == null) {
320 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
322 updateActiveInventoryCounters(result);
323 fetchDocumentForUpsert(result);
333 * Process entity type self links.
335 * @param operationResult the operation result
337 private void processEntityTypeSelfLinks(OperationResult operationResult) {
339 JsonNode rootNode = null;
341 final String jsonResult = operationResult.getResult();
343 if (jsonResult != null && jsonResult.length() > 0) {
346 rootNode = mapper.readTree(jsonResult);
347 } catch (IOException exc) {
348 String message = "Could not deserialize JSON (representing operation result) as node tree. "
349 + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
350 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
354 JsonNode resultData = rootNode.get("result-data");
355 ArrayNode resultDataArrayNode = null;
357 if (resultData.isArray()) {
358 resultDataArrayNode = (ArrayNode) resultData;
360 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
361 JsonNode element = null;
363 while (elementIterator.hasNext()) {
364 element = elementIterator.next();
366 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
367 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
369 OxmEntityDescriptor descriptor = null;
371 if (resourceType != null && resourceLink != null) {
372 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
374 if (descriptor == null) {
375 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
376 // go to next element in iterator
379 if (descriptor.hasCrossEntityReferences()) {
380 selflinks.add(new SelfLinkDescriptor(resourceLink,
381 SynchronizerConfiguration.DEPTH_ALL_MODIFIER, resourceType));
392 * By providing the entity type and a json node for the entity, determine the primary key name(s)
393 * + primary key value(s) sufficient to build an entity query string of the following format:
395 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
397 * @return - a composite string in the above format or null
399 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
401 OxmEntityDescriptor entityDescriptor = oxmModelLoader.getEntityDescriptor(entityType);
403 String queryString = null;
405 if (entityDescriptor != null) {
407 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeName();
408 final List<String> keyValues = new ArrayList<String>();
409 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
411 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames, "/") + ":"
412 + NodeUtils.concatArray(keyValues);
422 * Fetch document for upsert.
426 private void fetchDocumentForUpsert(NetworkTransaction txn) {
428 if (!txn.getOperationResult().wasSuccessful()) {
429 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
433 if (txn.getDescriptor().hasCrossEntityReferences()) {
435 final String jsonResult = txn.getOperationResult().getResult();
437 if (jsonResult != null && jsonResult.length() > 0) {
440 * Here's what we are going to do:
442 * <li>Extract primary key name and value from the parent type.
443 * <li>Extract the primary key and value from the nested child instance.
444 * <li>Build a generic query to discover the self-link for the nested-child-instance using
446 * <li>Set the self-link on the child.
447 * <li>Generate the id that will allow the elastic-search upsert to work.
448 * <li>Rinse and repeat.
451 OxmEntityDescriptor parentEntityDescriptor =
452 oxmModelLoader.getEntityDescriptor(txn.getEntityType());
454 if (parentEntityDescriptor != null) {
456 CrossEntityReference cerDefinition = parentEntityDescriptor.getCrossEntityReference();
458 if (cerDefinition != null) {
459 JsonNode convertedNode = null;
462 NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
464 final String parentEntityQueryString =
465 determineEntityQueryString(txn.getEntityType(), convertedNode);
467 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
469 NodeUtils.extractFieldValuesFromObject(convertedNode,
470 cerDefinition.getReferenceAttributes(), extractedParentEntityAttributeValues);
472 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
473 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
474 nestedTargetEntityInstances);
476 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
478 OxmEntityDescriptor cerDescriptor = oxmModelLoader
479 .getSearchableEntityDescriptor(cerDefinition.getTargetEntityType());
481 if (cerDescriptor != null) {
483 String childEntityType = cerDefinition.getTargetEntityType();
485 List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeName();
487 List<String> childKeyValues = new ArrayList<String>();
488 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames,
491 String childEntityQueryKeyString =
492 childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames, "/") + ":"
493 + NodeUtils.concatArray(childKeyValues);
496 * Build generic-query to query child instance self-link from AAI
498 List<String> orderedQueryKeyParams = new ArrayList<String>();
499 if (SERVICE_INSTANCE.equals(childEntityType)) {
500 orderedQueryKeyParams.clear();
501 orderedQueryKeyParams.add(childEntityQueryKeyString);
503 orderedQueryKeyParams.add(parentEntityQueryString);
504 orderedQueryKeyParams.add(childEntityQueryKeyString);
506 String genericQueryStr = null;
508 genericQueryStr = aaiDataProvider.getGenericQueryForSelfLink(childEntityType,
509 orderedQueryKeyParams);
511 if (genericQueryStr != null) {
512 aaiWorkOnHand.incrementAndGet();
513 OperationResult aaiQueryResult = aaiDataProvider
514 .queryActiveInventoryWithRetries(genericQueryStr, "application/json",
515 aaiConfig.getAaiRestConfig().getNumRequestRetries());
516 aaiWorkOnHand.decrementAndGet();
517 if (aaiQueryResult != null && aaiQueryResult.wasSuccessful()) {
519 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
520 JsonNode genericQueryResult = null;
523 NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
525 if (genericQueryResult != null) {
527 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link",
530 String selfLink = null;
532 if (entityLinks.size() != 1) {
534 * an ambiguity exists where we can't reliably determine the self
535 * link, this should be a permanent error
537 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY,
538 String.valueOf(entityLinks.size()));
540 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
542 if (!cerDescriptor.getSearchableAttributes().isEmpty()) {
544 IndexableCrossEntityReference icer =
545 getPopulatedDocument(targetEntityInstance, cerDescriptor);
547 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
548 icer.addCrossEntityReferenceValue(
549 parentCrossEntityReferenceAttributeValue);
552 icer.setLink(ActiveInventoryConfig.extractResourcePath(selfLink));
558 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
559 } catch (Exception exc) {
560 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
561 exc.getLocalizedMessage());
565 NetworkTransaction n2 = new NetworkTransaction();
567 n2.setEntityType(txn.getEntityType());
568 n2.setDescriptor(txn.getDescriptor());
569 n2.setOperationType(HttpMethod.GET);
571 esWorkOnHand.incrementAndGet();
573 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider),
574 esExecutor).whenComplete((result, error) -> {
576 esWorkOnHand.decrementAndGet();
579 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
580 error.getLocalizedMessage());
582 updateElasticSearchCounters(result);
583 performDocumentUpsert(result, icer);
590 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
593 } catch (Exception exc) {
594 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(),
595 exc.getLocalizedMessage());
599 String message = "Entity sync failed because AAI query failed with error ";
600 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
605 "Entity Sync failed because generic query str could not be determined.";
606 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
608 } catch (Exception exc) {
610 "Failed to sync entity because generation of generic query failed with error = "
612 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
618 } catch (IOException ioe) {
619 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
624 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
631 * Perform document upsert.
633 * @param esGetResult the es get result
634 * @param icer the icer
636 protected void performDocumentUpsert(NetworkTransaction esGetResult,
637 IndexableCrossEntityReference icer) {
641 * As part of the response processing we need to do the following:
642 * <li>1. Extract the version (if present), it will be the ETAG when we use the
643 * Search-Abstraction-Service
644 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
646 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
647 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
653 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
654 } catch (Exception exc) {
655 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
659 boolean wasEntryDiscovered = false;
660 String versionNumber = null;
661 if (esGetResult.getOperationResult().getResultCode() == 404) {
662 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
663 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
664 wasEntryDiscovered = true;
666 versionNumber = NodeUtils.extractFieldValueFromObject(
667 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
669 } catch (IOException exc) {
670 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
671 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
676 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
679 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
680 String.valueOf(esGetResult.getOperationResult().getResultCode()));
685 String jsonPayload = null;
686 if (wasEntryDiscovered) {
688 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
689 NodeUtils.extractObjectsByKey(
690 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
691 "_source", sourceObject);
693 if (!sourceObject.isEmpty()) {
694 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
695 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
696 ObjectReader updater = mapper.readerForUpdating(me);
697 MergableEntity merged = updater.readValue(icer.getIndexDocumentJson());
698 jsonPayload = mapper.writeValueAsString(merged);
700 } catch (IOException exc) {
701 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
702 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
706 jsonPayload = icer.getIndexDocumentJson();
709 if (wasEntryDiscovered) {
710 if (versionNumber != null && jsonPayload != null) {
712 String requestPayload = esDataProvider.buildBulkImportOperationRequest(getIndexName(),
713 ElasticSearchConfig.getConfig().getType(), icer.getId(), versionNumber, jsonPayload);
715 NetworkTransaction transactionTracker = new NetworkTransaction();
716 transactionTracker.setEntityType(esGetResult.getEntityType());
717 transactionTracker.setDescriptor(esGetResult.getDescriptor());
718 transactionTracker.setOperationType(HttpMethod.PUT);
720 esWorkOnHand.incrementAndGet();
721 supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
722 requestPayload, esDataProvider, transactionTracker), esPutExecutor)
723 .whenComplete((result, error) -> {
725 esWorkOnHand.decrementAndGet();
728 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
730 updateElasticSearchCounters(result);
731 processStoreDocumentResult(result, esGetResult, icer);
737 if (link != null && jsonPayload != null) {
739 NetworkTransaction updateElasticTxn = new NetworkTransaction();
740 updateElasticTxn.setLink(link);
741 updateElasticTxn.setEntityType(esGetResult.getEntityType());
742 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
743 updateElasticTxn.setOperationType(HttpMethod.PUT);
745 esWorkOnHand.incrementAndGet();
746 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
747 esPutExecutor).whenComplete((result, error) -> {
749 esWorkOnHand.decrementAndGet();
752 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
754 updateElasticSearchCounters(result);
755 processStoreDocumentResult(result, esGetResult, icer);
760 } catch (Exception exc) {
761 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
766 * Process store document result.
768 * @param esPutResult the es put result
769 * @param esGetResult the es get result
770 * @param icer the icer
772 private void processStoreDocumentResult(NetworkTransaction esPutResult,
773 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
775 OperationResult or = esPutResult.getOperationResult();
777 if (!or.wasSuccessful()) {
778 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
780 if (shouldAllowRetry(icer.getId())) {
782 esWorkOnHand.incrementAndGet();
784 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
785 retryQueue.push(rsc);
787 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
790 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
797 * Perform retry sync.
799 private void performRetrySync() {
800 while (retryQueue.peek() != null) {
802 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
805 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
806 NetworkTransaction txn = rsc.getNetworkTransaction();
810 // In this retry flow the icer object has already
811 // derived its fields
812 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
813 } catch (Exception exc) {
814 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
818 NetworkTransaction retryTransaction = new NetworkTransaction();
819 retryTransaction.setLink(link);
820 retryTransaction.setEntityType(txn.getEntityType());
821 retryTransaction.setDescriptor(txn.getDescriptor());
822 retryTransaction.setOperationType(HttpMethod.GET);
825 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
826 * that for this request already when queuing the failed PUT!
829 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
830 esExecutor).whenComplete((result, error) -> {
832 esWorkOnHand.decrementAndGet();
835 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
837 updateElasticSearchCounters(result);
838 performDocumentUpsert(result, icer);
848 * Should allow retry.
851 * @return true, if successful
853 private boolean shouldAllowRetry(String id) {
854 boolean isRetryAllowed = true;
855 if (retryLimitTracker.get(id) != null) {
856 Integer currentCount = retryLimitTracker.get(id);
857 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
858 isRetryAllowed = false;
859 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
861 Integer newCount = new Integer(currentCount.intValue() + 1);
862 retryLimitTracker.put(id, newCount);
866 Integer firstRetryCount = new Integer(1);
867 retryLimitTracker.put(id, firstRetryCount);
870 return isRetryAllowed;
874 * Gets the populated document.
876 * @param entityNode the entity node
877 * @param resultDescriptor the result descriptor
878 * @return the populated document
879 * @throws JsonProcessingException the json processing exception
880 * @throws IOException Signals that an I/O exception has occurred.
882 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
883 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
885 IndexableCrossEntityReference icer = new IndexableCrossEntityReference(oxmModelLoader);
887 icer.setEntityType(resultDescriptor.getEntityName());
889 List<String> primaryKeyValues = new ArrayList<String>();
890 String pkeyValue = null;
892 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
893 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
894 if (pkeyValue != null) {
895 primaryKeyValues.add(pkeyValue);
897 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
901 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
902 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);