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.openecomp.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.openecomp.cl.api.Logger;
42 import org.openecomp.cl.eelf.LoggerFactory;
43 import org.openecomp.sparky.config.oxm.CrossEntityReference;
44 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
45 import org.openecomp.sparky.dal.NetworkTransaction;
46 import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
47 import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
48 import org.openecomp.sparky.dal.rest.HttpMethod;
49 import org.openecomp.sparky.dal.rest.OperationResult;
50 import org.openecomp.sparky.logging.AaiUiMsgs;
51 import org.openecomp.sparky.synchronizer.config.SynchronizerConfiguration;
52 import org.openecomp.sparky.synchronizer.entity.IndexableCrossEntityReference;
53 import org.openecomp.sparky.synchronizer.entity.MergableEntity;
54 import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
55 import org.openecomp.sparky.synchronizer.enumeration.OperationState;
56 import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState;
57 import org.openecomp.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
58 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchPut;
59 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchRetrieval;
60 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchUpdate;
61 import org.openecomp.sparky.util.NodeUtils;
64 import org.openecomp.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.openecomp.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.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
165 public String getStatReport(boolean showFinalReport) {
166 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
167 return getStatReport(syncDurationInMs, showFinalReport);
171 * @see org.openecomp.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 // TODO // TODO -> LOG, waht should be logged here?
344 JsonNode resultData = rootNode.get("result-data");
345 ArrayNode resultDataArrayNode = null;
347 if (resultData.isArray()) {
348 resultDataArrayNode = (ArrayNode) resultData;
350 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
351 JsonNode element = null;
353 while (elementIterator.hasNext()) {
354 element = elementIterator.next();
356 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
357 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
359 OxmEntityDescriptor descriptor = null;
361 if (resourceType != null && resourceLink != null) {
362 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
364 if (descriptor == null) {
365 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
366 // go to next element in iterator
369 if (descriptor.hasCrossEntityReferences()) {
370 selflinks.add(new SelfLinkDescriptor(
371 resourceLink,SynchronizerConfiguration.DEPTH_ALL_MODIFIER, resourceType));
382 * By providing the entity type and a json node for the entity, determine the
383 * primary key name(s) + primary key value(s) sufficient to build an entity query string
384 * of the following format:
386 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
388 * @return - a composite string in the above format or null
390 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
392 OxmEntityDescriptor entityDescriptor =
393 oxmModelLoader.getEntityDescriptor(entityType);
395 String queryString = null;
397 if ( entityDescriptor != null ) {
399 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeName();
400 final List<String> keyValues = new ArrayList<String>();
401 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
403 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
413 * Fetch document for upsert.
417 private void fetchDocumentForUpsert(NetworkTransaction txn) {
419 if (!txn.getOperationResult().wasSuccessful()) {
420 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
424 if (txn.getDescriptor().hasCrossEntityReferences()) {
426 final String jsonResult = txn.getOperationResult().getResult();
428 if (jsonResult != null && jsonResult.length() > 0) {
431 * Here's what we are going to do:
433 * <li>Extract primary key name and value from the parent type.
434 * <li>Extract the primary key and value from the nested child instance.
435 * <li>Build a generic query to discover the self-link for the nested-child-instance using
437 * <li>Set the self-link on the child.
438 * <li>Generate the id that will allow the elastic-search upsert to work.
439 * <li>Rinse and repeat.
442 OxmEntityDescriptor parentEntityDescriptor =
443 oxmModelLoader.getEntityDescriptor(txn.getEntityType());
445 if ( parentEntityDescriptor != null ) {
447 CrossEntityReference cerDefinition = parentEntityDescriptor.getCrossEntityReference();
449 if (cerDefinition != null) {
450 JsonNode convertedNode = null;
452 convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
454 final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
456 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
458 NodeUtils.extractFieldValuesFromObject(convertedNode,
459 cerDefinition.getReferenceAttributes(),
460 extractedParentEntityAttributeValues);
462 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
463 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
464 nestedTargetEntityInstances);
466 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
468 OxmEntityDescriptor cerDescriptor =
469 oxmModelLoader.getSearchableEntityDescriptor(cerDefinition.getTargetEntityType());
471 if (cerDescriptor != null) {
473 String childEntityType = cerDefinition.getTargetEntityType();
475 List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeName();
477 List<String> childKeyValues = new ArrayList<String>();
478 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
480 String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
483 * Build generic-query to query child instance self-link from AAI
485 List<String> orderedQueryKeyParams = new ArrayList<String>();
486 if (SERVICE_INSTANCE.equals(childEntityType)) {
487 orderedQueryKeyParams.clear();
488 orderedQueryKeyParams.add(childEntityQueryKeyString);
490 orderedQueryKeyParams.add(parentEntityQueryString);
491 orderedQueryKeyParams.add(childEntityQueryKeyString);
493 String genericQueryStr = null;
495 genericQueryStr = aaiDataProvider.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
497 if (genericQueryStr != null) {
498 aaiWorkOnHand.incrementAndGet();
499 OperationResult aaiQueryResult = aaiDataProvider.queryActiveInventoryWithRetries(
500 genericQueryStr, "application/json",
501 aaiConfig.getAaiRestConfig().getNumRequestRetries());
502 aaiWorkOnHand.decrementAndGet();
503 if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
505 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
506 JsonNode genericQueryResult = null;
508 genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
510 if ( genericQueryResult != null ) {
512 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
514 String selfLink = null;
516 if (entityLinks.size() != 1) {
518 * an ambiguity exists where we can't reliably determine the self
519 * link, this should be a permanent error
521 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
523 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
525 if (!cerDescriptor.getSearchableAttributes().isEmpty()) {
527 IndexableCrossEntityReference icer =
528 getPopulatedDocument(targetEntityInstance, cerDescriptor);
530 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
531 icer.addCrossEntityReferenceValue(
532 parentCrossEntityReferenceAttributeValue);
535 icer.setLink(ActiveInventoryConfig.extractResourcePath(selfLink));
541 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
542 } catch (Exception exc) {
543 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
547 NetworkTransaction n2 = new NetworkTransaction();
549 n2.setEntityType(txn.getEntityType());
550 n2.setDescriptor(txn.getDescriptor());
551 n2.setOperationType(HttpMethod.GET);
553 esWorkOnHand.incrementAndGet();
555 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider),
556 esExecutor).whenComplete((result, error) -> {
558 esWorkOnHand.decrementAndGet();
561 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
563 updateElasticSearchCounters(result);
564 performDocumentUpsert(result, icer);
571 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
574 } catch (Exception exc) {
575 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
579 String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult();
580 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
584 String message = "Entity Sync failed because generic query str could not be determined.";
585 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
587 } catch (Exception exc) {
588 String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
589 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
595 } catch (IOException ioe) {
596 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
601 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
608 * Perform document upsert.
610 * @param esGetResult the es get result
611 * @param icer the icer
613 protected void performDocumentUpsert(NetworkTransaction esGetResult,
614 IndexableCrossEntityReference icer) {
618 * As part of the response processing we need to do the following:
619 * <li>1. Extract the version (if present), it will be the ETAG when we use the
620 * Search-Abstraction-Service
621 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
623 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
624 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
630 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
631 } catch (Exception exc) {
632 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
636 boolean wasEntryDiscovered = false;
637 String versionNumber = null;
638 if (esGetResult.getOperationResult().getResultCode() == 404) {
639 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
640 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
641 wasEntryDiscovered = true;
643 versionNumber = NodeUtils.extractFieldValueFromObject(
644 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
646 } catch (IOException exc) {
647 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
648 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
653 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
656 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
657 String.valueOf(esGetResult.getOperationResult().getResultCode()));
662 String jsonPayload = null;
663 if (wasEntryDiscovered) {
665 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
666 NodeUtils.extractObjectsByKey(
667 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
668 "_source", sourceObject);
670 if (!sourceObject.isEmpty()) {
671 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
672 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
673 ObjectReader updater = mapper.readerForUpdating(me);
674 MergableEntity merged = updater.readValue(icer.getIndexDocumentJson());
675 jsonPayload = mapper.writeValueAsString(merged);
677 } catch (IOException exc) {
678 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
679 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
683 jsonPayload = icer.getIndexDocumentJson();
686 if (wasEntryDiscovered) {
687 if (versionNumber != null && jsonPayload != null) {
689 String requestPayload = esDataProvider.buildBulkImportOperationRequest(getIndexName(),
690 ElasticSearchConfig.getConfig().getType(), icer.getId(), versionNumber, jsonPayload);
692 NetworkTransaction transactionTracker = new NetworkTransaction();
693 transactionTracker.setEntityType(esGetResult.getEntityType());
694 transactionTracker.setDescriptor(esGetResult.getDescriptor());
695 transactionTracker.setOperationType(HttpMethod.PUT);
697 esWorkOnHand.incrementAndGet();
698 supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
699 requestPayload, esDataProvider, transactionTracker), esPutExecutor)
700 .whenComplete((result, error) -> {
702 esWorkOnHand.decrementAndGet();
705 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
707 updateElasticSearchCounters(result);
708 processStoreDocumentResult(result, esGetResult, icer);
714 if (link != null && jsonPayload != null) {
716 NetworkTransaction updateElasticTxn = new NetworkTransaction();
717 updateElasticTxn.setLink(link);
718 updateElasticTxn.setEntityType(esGetResult.getEntityType());
719 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
720 updateElasticTxn.setOperationType(HttpMethod.PUT);
722 esWorkOnHand.incrementAndGet();
723 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
724 esPutExecutor).whenComplete((result, error) -> {
726 esWorkOnHand.decrementAndGet();
729 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
731 updateElasticSearchCounters(result);
732 processStoreDocumentResult(result, esGetResult, icer);
737 } catch (Exception exc) {
738 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
743 * Process store document result.
745 * @param esPutResult the es put result
746 * @param esGetResult the es get result
747 * @param icer the icer
749 private void processStoreDocumentResult(NetworkTransaction esPutResult,
750 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
752 OperationResult or = esPutResult.getOperationResult();
754 if (!or.wasSuccessful()) {
755 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
757 if (shouldAllowRetry(icer.getId())) {
759 esWorkOnHand.incrementAndGet();
761 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
762 retryQueue.push(rsc);
764 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
767 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
774 * Perform retry sync.
776 private void performRetrySync() {
777 while (retryQueue.peek() != null) {
779 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
782 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
783 NetworkTransaction txn = rsc.getNetworkTransaction();
787 // In this retry flow the icer object has already
788 // derived its fields
789 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
790 } catch (Exception exc) {
791 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
795 NetworkTransaction retryTransaction = new NetworkTransaction();
796 retryTransaction.setLink(link);
797 retryTransaction.setEntityType(txn.getEntityType());
798 retryTransaction.setDescriptor(txn.getDescriptor());
799 retryTransaction.setOperationType(HttpMethod.GET);
802 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
803 * that for this request already when queuing the failed PUT!
806 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
807 esExecutor).whenComplete((result, error) -> {
809 esWorkOnHand.decrementAndGet();
812 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
814 updateElasticSearchCounters(result);
815 performDocumentUpsert(result, icer);
825 * Should allow retry.
828 * @return true, if successful
830 private boolean shouldAllowRetry(String id) {
831 boolean isRetryAllowed = true;
832 if (retryLimitTracker.get(id) != null) {
833 Integer currentCount = retryLimitTracker.get(id);
834 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
835 isRetryAllowed = false;
836 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
838 Integer newCount = new Integer(currentCount.intValue() + 1);
839 retryLimitTracker.put(id, newCount);
843 Integer firstRetryCount = new Integer(1);
844 retryLimitTracker.put(id, firstRetryCount);
847 return isRetryAllowed;
851 * Gets the populated document.
853 * @param entityNode the entity node
854 * @param resultDescriptor the result descriptor
855 * @return the populated document
856 * @throws JsonProcessingException the json processing exception
857 * @throws IOException Signals that an I/O exception has occurred.
859 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
860 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
862 IndexableCrossEntityReference icer = new IndexableCrossEntityReference(oxmModelLoader);
864 icer.setEntityType(resultDescriptor.getEntityName());
866 List<String> primaryKeyValues = new ArrayList<String>();
867 String pkeyValue = null;
869 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
870 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
871 if (pkeyValue != null) {
872 primaryKeyValues.add(pkeyValue);
874 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
878 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
879 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);