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) throws Exception {
122 super(LOG, "CERS", 2, 5, 5, indexName);
123 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
124 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
125 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
126 this.synchronizerName = "Cross Reference Entity Synchronizer";
127 this.isAllWorkEnumerated = false;
128 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
129 this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(
130 oxmModelLoader.getCrossReferenceEntityDescriptors());
131 this.esEntityStats.initializeCountersFromOxmEntityDescriptors(
132 oxmModelLoader.getCrossReferenceEntityDescriptors());
133 this.aaiConfig = aaiConfig;
134 this.syncDurationInMs = -1;
138 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync()
141 public OperationState doSync() {
142 this.syncDurationInMs = -1;
143 String txnID = NodeUtils.getRandomTxnId();
144 MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
147 syncStartedTimeStampInMs = System.currentTimeMillis();
149 return OperationState.OK;
153 public SynchronizerState getState() {
155 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
158 return SynchronizerState.IDLE;
162 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
165 public String getStatReport(boolean showFinalReport) {
166 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
167 return getStatReport(syncDurationInMs, showFinalReport);
171 * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown()
174 public void shutdown() {
175 this.shutdownExecutors();
179 protected boolean isSyncDone() {
180 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
182 if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
192 * @return the operation state
194 private OperationState launchSyncFlow() {
195 final Map<String,String> contextMap = MDC.getCopyOfContextMap();
196 Map<String, OxmEntityDescriptor> descriptorMap =
197 oxmModelLoader.getCrossReferenceEntityDescriptors();
199 if (descriptorMap.isEmpty()) {
200 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
202 return OperationState.ERROR;
205 Collection<String> syncTypes = descriptorMap.keySet();
210 * launch a parallel async thread to process the documents for each entity-type (to max the of
211 * the configured executor anyway)
214 aaiWorkOnHand.set(syncTypes.size());
216 for (String key : syncTypes) {
218 supplyAsync(new Supplier<Void>() {
222 MDC.setContextMap(contextMap);
223 OperationResult typeLinksResult = null;
225 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
226 aaiWorkOnHand.decrementAndGet();
227 processEntityTypeSelfLinks(typeLinksResult);
228 } catch (Exception exc) {
229 // TODO -> LOG, what should be logged here?
235 }, aaiExecutor).whenComplete((result, error) -> {
237 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
242 while (aaiWorkOnHand.get() != 0) {
244 if (LOG.isDebugEnabled()) {
245 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
251 aaiWorkOnHand.set(selflinks.size());
252 isAllWorkEnumerated = true;
255 while (!isSyncDone()) {
261 * Make sure we don't hang on to retries that failed which could cause issues during future
264 retryLimitTracker.clear();
266 } catch (Exception exc) {
267 // TODO -> LOG, waht should be logged here?
270 return OperationState.OK;
276 private void performSync() {
277 while (selflinks.peek() != null) {
279 SelfLinkDescriptor linkDescriptor = selflinks.poll();
280 aaiWorkOnHand.decrementAndGet();
282 OxmEntityDescriptor descriptor = null;
284 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
286 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
288 if (descriptor == null) {
289 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
290 // go to next element in iterator
294 if (descriptor.hasCrossEntityReferences()) {
296 NetworkTransaction txn = new NetworkTransaction();
297 txn.setDescriptor(descriptor);
298 txn.setLink(linkDescriptor.getSelfLink() + linkDescriptor.getDepthModifier());
299 txn.setOperationType(HttpMethod.GET);
300 txn.setEntityType(linkDescriptor.getEntityType());
302 aaiWorkOnHand.incrementAndGet();
304 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
305 .whenComplete((result, error) -> {
307 aaiWorkOnHand.decrementAndGet();
310 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
312 if (result == null) {
313 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
315 updateActiveInventoryCounters(result);
316 fetchDocumentForUpsert(result);
326 * Process entity type self links.
328 * @param operationResult the operation result
330 private void processEntityTypeSelfLinks(OperationResult operationResult) {
332 JsonNode rootNode = null;
334 final String jsonResult = operationResult.getResult();
336 if (jsonResult != null && jsonResult.length() > 0) {
339 rootNode = mapper.readTree(jsonResult);
340 } catch (IOException exc) {
341 String message = "Could not deserialize JSON (representing operation result) as node tree. "
342 + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
343 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
347 JsonNode resultData = rootNode.get("result-data");
348 ArrayNode resultDataArrayNode = null;
350 if (resultData.isArray()) {
351 resultDataArrayNode = (ArrayNode) resultData;
353 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
354 JsonNode element = null;
356 while (elementIterator.hasNext()) {
357 element = elementIterator.next();
359 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
360 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
362 OxmEntityDescriptor descriptor = null;
364 if (resourceType != null && resourceLink != null) {
365 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
367 if (descriptor == null) {
368 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
369 // go to next element in iterator
372 if (descriptor.hasCrossEntityReferences()) {
373 selflinks.add(new SelfLinkDescriptor(
374 resourceLink,SynchronizerConfiguration.DEPTH_ALL_MODIFIER, resourceType));
385 * By providing the entity type and a json node for the entity, determine the
386 * primary key name(s) + primary key value(s) sufficient to build an entity query string
387 * of the following format:
389 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
391 * @return - a composite string in the above format or null
393 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
395 OxmEntityDescriptor entityDescriptor =
396 oxmModelLoader.getEntityDescriptor(entityType);
398 String queryString = null;
400 if ( entityDescriptor != null ) {
402 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeName();
403 final List<String> keyValues = new ArrayList<String>();
404 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
406 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
416 * Fetch document for upsert.
420 private void fetchDocumentForUpsert(NetworkTransaction txn) {
422 if (!txn.getOperationResult().wasSuccessful()) {
423 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
427 if (txn.getDescriptor().hasCrossEntityReferences()) {
429 final String jsonResult = txn.getOperationResult().getResult();
431 if (jsonResult != null && jsonResult.length() > 0) {
434 * Here's what we are going to do:
436 * <li>Extract primary key name and value from the parent type.
437 * <li>Extract the primary key and value from the nested child instance.
438 * <li>Build a generic query to discover the self-link for the nested-child-instance using
440 * <li>Set the self-link on the child.
441 * <li>Generate the id that will allow the elastic-search upsert to work.
442 * <li>Rinse and repeat.
445 OxmEntityDescriptor parentEntityDescriptor =
446 oxmModelLoader.getEntityDescriptor(txn.getEntityType());
448 if ( parentEntityDescriptor != null ) {
450 CrossEntityReference cerDefinition = parentEntityDescriptor.getCrossEntityReference();
452 if (cerDefinition != null) {
453 JsonNode convertedNode = null;
455 convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
457 final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
459 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
461 NodeUtils.extractFieldValuesFromObject(convertedNode,
462 cerDefinition.getReferenceAttributes(),
463 extractedParentEntityAttributeValues);
465 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
466 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
467 nestedTargetEntityInstances);
469 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
471 OxmEntityDescriptor cerDescriptor =
472 oxmModelLoader.getSearchableEntityDescriptor(cerDefinition.getTargetEntityType());
474 if (cerDescriptor != null) {
476 String childEntityType = cerDefinition.getTargetEntityType();
478 List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeName();
480 List<String> childKeyValues = new ArrayList<String>();
481 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
483 String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
486 * Build generic-query to query child instance self-link from AAI
488 List<String> orderedQueryKeyParams = new ArrayList<String>();
489 if (SERVICE_INSTANCE.equals(childEntityType)) {
490 orderedQueryKeyParams.clear();
491 orderedQueryKeyParams.add(childEntityQueryKeyString);
493 orderedQueryKeyParams.add(parentEntityQueryString);
494 orderedQueryKeyParams.add(childEntityQueryKeyString);
496 String genericQueryStr = null;
498 genericQueryStr = aaiDataProvider.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
500 if (genericQueryStr != null) {
501 aaiWorkOnHand.incrementAndGet();
502 OperationResult aaiQueryResult = aaiDataProvider.queryActiveInventoryWithRetries(
503 genericQueryStr, "application/json",
504 aaiConfig.getAaiRestConfig().getNumRequestRetries());
505 aaiWorkOnHand.decrementAndGet();
506 if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
508 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
509 JsonNode genericQueryResult = null;
511 genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
513 if ( genericQueryResult != null ) {
515 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
517 String selfLink = null;
519 if (entityLinks.size() != 1) {
521 * an ambiguity exists where we can't reliably determine the self
522 * link, this should be a permanent error
524 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
526 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
528 if (!cerDescriptor.getSearchableAttributes().isEmpty()) {
530 IndexableCrossEntityReference icer =
531 getPopulatedDocument(targetEntityInstance, cerDescriptor);
533 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
534 icer.addCrossEntityReferenceValue(
535 parentCrossEntityReferenceAttributeValue);
538 icer.setLink(ActiveInventoryConfig.extractResourcePath(selfLink));
544 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
545 } catch (Exception exc) {
546 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
550 NetworkTransaction n2 = new NetworkTransaction();
552 n2.setEntityType(txn.getEntityType());
553 n2.setDescriptor(txn.getDescriptor());
554 n2.setOperationType(HttpMethod.GET);
556 esWorkOnHand.incrementAndGet();
558 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider),
559 esExecutor).whenComplete((result, error) -> {
561 esWorkOnHand.decrementAndGet();
564 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
566 updateElasticSearchCounters(result);
567 performDocumentUpsert(result, icer);
574 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
577 } catch (Exception exc) {
578 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
582 String message = "Entity sync failed because AAI query failed with error ";
583 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
587 String message = "Entity Sync failed because generic query str could not be determined.";
588 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
590 } catch (Exception exc) {
591 String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
592 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
598 } catch (IOException ioe) {
599 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
604 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
611 * Perform document upsert.
613 * @param esGetResult the es get result
614 * @param icer the icer
616 protected void performDocumentUpsert(NetworkTransaction esGetResult,
617 IndexableCrossEntityReference icer) {
621 * As part of the response processing we need to do the following:
622 * <li>1. Extract the version (if present), it will be the ETAG when we use the
623 * Search-Abstraction-Service
624 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
626 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
627 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
633 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
634 } catch (Exception exc) {
635 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
639 boolean wasEntryDiscovered = false;
640 String versionNumber = null;
641 if (esGetResult.getOperationResult().getResultCode() == 404) {
642 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
643 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
644 wasEntryDiscovered = true;
646 versionNumber = NodeUtils.extractFieldValueFromObject(
647 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
649 } catch (IOException exc) {
650 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
651 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
656 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
659 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
660 String.valueOf(esGetResult.getOperationResult().getResultCode()));
665 String jsonPayload = null;
666 if (wasEntryDiscovered) {
668 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
669 NodeUtils.extractObjectsByKey(
670 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
671 "_source", sourceObject);
673 if (!sourceObject.isEmpty()) {
674 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
675 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
676 ObjectReader updater = mapper.readerForUpdating(me);
677 MergableEntity merged = updater.readValue(icer.getIndexDocumentJson());
678 jsonPayload = mapper.writeValueAsString(merged);
680 } catch (IOException exc) {
681 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
682 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
686 jsonPayload = icer.getIndexDocumentJson();
689 if (wasEntryDiscovered) {
690 if (versionNumber != null && jsonPayload != null) {
692 String requestPayload = esDataProvider.buildBulkImportOperationRequest(getIndexName(),
693 ElasticSearchConfig.getConfig().getType(), icer.getId(), versionNumber, jsonPayload);
695 NetworkTransaction transactionTracker = new NetworkTransaction();
696 transactionTracker.setEntityType(esGetResult.getEntityType());
697 transactionTracker.setDescriptor(esGetResult.getDescriptor());
698 transactionTracker.setOperationType(HttpMethod.PUT);
700 esWorkOnHand.incrementAndGet();
701 supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
702 requestPayload, esDataProvider, transactionTracker), esPutExecutor)
703 .whenComplete((result, error) -> {
705 esWorkOnHand.decrementAndGet();
708 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
710 updateElasticSearchCounters(result);
711 processStoreDocumentResult(result, esGetResult, icer);
717 if (link != null && jsonPayload != null) {
719 NetworkTransaction updateElasticTxn = new NetworkTransaction();
720 updateElasticTxn.setLink(link);
721 updateElasticTxn.setEntityType(esGetResult.getEntityType());
722 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
723 updateElasticTxn.setOperationType(HttpMethod.PUT);
725 esWorkOnHand.incrementAndGet();
726 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
727 esPutExecutor).whenComplete((result, error) -> {
729 esWorkOnHand.decrementAndGet();
732 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
734 updateElasticSearchCounters(result);
735 processStoreDocumentResult(result, esGetResult, icer);
740 } catch (Exception exc) {
741 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
746 * Process store document result.
748 * @param esPutResult the es put result
749 * @param esGetResult the es get result
750 * @param icer the icer
752 private void processStoreDocumentResult(NetworkTransaction esPutResult,
753 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
755 OperationResult or = esPutResult.getOperationResult();
757 if (!or.wasSuccessful()) {
758 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
760 if (shouldAllowRetry(icer.getId())) {
762 esWorkOnHand.incrementAndGet();
764 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
765 retryQueue.push(rsc);
767 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
770 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
777 * Perform retry sync.
779 private void performRetrySync() {
780 while (retryQueue.peek() != null) {
782 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
785 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
786 NetworkTransaction txn = rsc.getNetworkTransaction();
790 // In this retry flow the icer object has already
791 // derived its fields
792 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
793 } catch (Exception exc) {
794 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
798 NetworkTransaction retryTransaction = new NetworkTransaction();
799 retryTransaction.setLink(link);
800 retryTransaction.setEntityType(txn.getEntityType());
801 retryTransaction.setDescriptor(txn.getDescriptor());
802 retryTransaction.setOperationType(HttpMethod.GET);
805 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
806 * that for this request already when queuing the failed PUT!
809 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
810 esExecutor).whenComplete((result, error) -> {
812 esWorkOnHand.decrementAndGet();
815 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
817 updateElasticSearchCounters(result);
818 performDocumentUpsert(result, icer);
828 * Should allow retry.
831 * @return true, if successful
833 private boolean shouldAllowRetry(String id) {
834 boolean isRetryAllowed = true;
835 if (retryLimitTracker.get(id) != null) {
836 Integer currentCount = retryLimitTracker.get(id);
837 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
838 isRetryAllowed = false;
839 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
841 Integer newCount = new Integer(currentCount.intValue() + 1);
842 retryLimitTracker.put(id, newCount);
846 Integer firstRetryCount = new Integer(1);
847 retryLimitTracker.put(id, firstRetryCount);
850 return isRetryAllowed;
854 * Gets the populated document.
856 * @param entityNode the entity node
857 * @param resultDescriptor the result descriptor
858 * @return the populated document
859 * @throws JsonProcessingException the json processing exception
860 * @throws IOException Signals that an I/O exception has occurred.
862 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
863 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
865 IndexableCrossEntityReference icer = new IndexableCrossEntityReference(oxmModelLoader);
867 icer.setEntityType(resultDescriptor.getEntityName());
869 List<String> primaryKeyValues = new ArrayList<String>();
870 String pkeyValue = null;
872 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
873 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
874 if (pkeyValue != null) {
875 primaryKeyValues.add(pkeyValue);
877 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
881 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
882 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);