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.Collection;
35 import java.util.Deque;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.ConcurrentLinkedDeque;
41 import java.util.concurrent.ExecutorService;
42 import java.util.function.Supplier;
44 import org.openecomp.cl.api.Logger;
45 import org.openecomp.cl.eelf.LoggerFactory;
46 import org.openecomp.sparky.config.oxm.CrossEntityReference;
47 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
48 import org.openecomp.sparky.dal.NetworkTransaction;
49 import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
50 import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
51 import org.openecomp.sparky.dal.rest.HttpMethod;
52 import org.openecomp.sparky.dal.rest.OperationResult;
53 import org.openecomp.sparky.logging.AaiUiMsgs;
54 import org.openecomp.sparky.synchronizer.config.SynchronizerConfiguration;
55 import org.openecomp.sparky.synchronizer.entity.IndexableCrossEntityReference;
56 import org.openecomp.sparky.synchronizer.entity.MergableEntity;
57 import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
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.synchronizer.task.PerformElasticSearchUpdate;
64 import org.openecomp.sparky.util.NodeUtils;
67 import org.openecomp.cl.mdc.MdcContext;
68 import com.fasterxml.jackson.core.JsonProcessingException;
69 import com.fasterxml.jackson.databind.JsonNode;
70 import com.fasterxml.jackson.databind.ObjectReader;
71 import com.fasterxml.jackson.databind.node.ArrayNode;
74 * The Class CrossEntityReferenceSynchronizer.
76 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
77 implements IndexSynchronizer {
80 * The Class RetryCrossEntitySyncContainer.
82 private class RetryCrossEntitySyncContainer {
83 NetworkTransaction txn;
84 IndexableCrossEntityReference icer;
87 * Instantiates a new retry cross entity sync container.
90 * @param icer the icer
92 public RetryCrossEntitySyncContainer(NetworkTransaction txn,
93 IndexableCrossEntityReference icer) {
98 public NetworkTransaction getNetworkTransaction() {
102 public IndexableCrossEntityReference getIndexableCrossEntityReference() {
107 private static final Logger LOG =
108 LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
110 private static final String SERVICE_INSTANCE = "service-instance";
111 private Deque<SelfLinkDescriptor> selflinks;
112 private Deque<RetryCrossEntitySyncContainer> retryQueue;
113 private Map<String, Integer> retryLimitTracker;
114 private boolean isAllWorkEnumerated;
115 protected ExecutorService esPutExecutor;
116 protected ActiveInventoryConfig aaiConfig;
119 * Instantiates a new cross entity reference synchronizer.
121 * @param indexName the index name
122 * @throws Exception the exception
124 public CrossEntityReferenceSynchronizer(String indexName, ActiveInventoryConfig aaiConfig) throws Exception {
125 super(LOG, "CERS", 2, 5, 5, indexName);
126 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
127 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
128 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
129 this.synchronizerName = "Cross Reference Entity Synchronizer";
130 this.isAllWorkEnumerated = false;
131 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
132 this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(
133 oxmModelLoader.getCrossReferenceEntityDescriptors());
134 this.esEntityStats.initializeCountersFromOxmEntityDescriptors(
135 oxmModelLoader.getCrossReferenceEntityDescriptors());
136 this.aaiConfig = aaiConfig;
137 this.syncDurationInMs = -1;
141 * @see org.openecomp.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;
165 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
168 public String getStatReport(boolean showFinalReport) {
169 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
170 return getStatReport(syncDurationInMs, showFinalReport);
174 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
177 public void shutdown() {
178 this.shutdownExecutors();
182 protected boolean isSyncDone() {
183 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
185 if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
195 * @return the operation state
197 private OperationState launchSyncFlow() {
198 final Map<String,String> contextMap = MDC.getCopyOfContextMap();
199 Map<String, OxmEntityDescriptor> descriptorMap =
200 oxmModelLoader.getCrossReferenceEntityDescriptors();
202 if (descriptorMap.isEmpty()) {
203 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
205 return OperationState.ERROR;
208 Collection<String> syncTypes = descriptorMap.keySet();
213 * launch a parallel async thread to process the documents for each entity-type (to max the of
214 * the configured executor anyway)
217 aaiWorkOnHand.set(syncTypes.size());
219 for (String key : syncTypes) {
221 supplyAsync(new Supplier<Void>() {
225 MDC.setContextMap(contextMap);
226 OperationResult typeLinksResult = null;
228 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
229 aaiWorkOnHand.decrementAndGet();
230 processEntityTypeSelfLinks(typeLinksResult);
231 } catch (Exception exc) {
232 // TODO -> LOG, what should be logged here?
238 }, aaiExecutor).whenComplete((result, error) -> {
240 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
245 while (aaiWorkOnHand.get() != 0) {
247 if (LOG.isDebugEnabled()) {
248 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
254 aaiWorkOnHand.set(selflinks.size());
255 isAllWorkEnumerated = true;
258 while (!isSyncDone()) {
264 * Make sure we don't hang on to retries that failed which could cause issues during future
267 retryLimitTracker.clear();
269 } catch (Exception exc) {
270 // TODO -> LOG, waht should be logged here?
273 return OperationState.OK;
279 private void performSync() {
280 while (selflinks.peek() != null) {
282 SelfLinkDescriptor linkDescriptor = selflinks.poll();
283 aaiWorkOnHand.decrementAndGet();
285 OxmEntityDescriptor descriptor = null;
287 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
289 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
291 if (descriptor == null) {
292 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
293 // go to next element in iterator
297 if (descriptor.hasCrossEntityReferences()) {
299 NetworkTransaction txn = new NetworkTransaction();
300 txn.setDescriptor(descriptor);
301 txn.setLink(linkDescriptor.getSelfLink() + linkDescriptor.getDepthModifier());
302 txn.setOperationType(HttpMethod.GET);
303 txn.setEntityType(linkDescriptor.getEntityType());
305 aaiWorkOnHand.incrementAndGet();
307 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
308 .whenComplete((result, error) -> {
310 aaiWorkOnHand.decrementAndGet();
313 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
315 if (result == null) {
316 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
318 updateActiveInventoryCounters(result);
319 fetchDocumentForUpsert(result);
329 * Process entity type self links.
331 * @param operationResult the operation result
333 private void processEntityTypeSelfLinks(OperationResult operationResult) {
335 JsonNode rootNode = null;
337 final String jsonResult = operationResult.getResult();
339 if (jsonResult != null && jsonResult.length() > 0) {
342 rootNode = mapper.readTree(jsonResult);
343 } catch (IOException exc) {
344 // TODO // TODO -> LOG, waht should be logged here?
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 " + aaiQueryResult.getResult();
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);