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.crossentityreference.sync;
25 import static java.util.concurrent.CompletableFuture.supplyAsync;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Deque;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.concurrent.ConcurrentLinkedDeque;
36 import java.util.concurrent.ExecutorService;
37 import java.util.function.Supplier;
39 import org.onap.aai.cl.api.Logger;
40 import org.onap.aai.cl.eelf.LoggerFactory;
41 import org.onap.aai.cl.mdc.MdcContext;
42 import org.onap.aai.restclient.client.OperationResult;
43 import org.onap.aai.sparky.config.oxm.CrossEntityReference;
44 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceDescriptor;
45 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceLookup;
46 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
47 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
48 import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
49 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
50 import org.onap.aai.sparky.dal.NetworkTransaction;
51 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig;
52 import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
53 import org.onap.aai.sparky.dal.rest.HttpMethod;
54 import org.onap.aai.sparky.logging.AaiUiMsgs;
55 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
56 import org.onap.aai.sparky.sync.IndexSynchronizer;
57 import org.onap.aai.sparky.sync.SynchronizerConstants;
58 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
59 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
60 import org.onap.aai.sparky.sync.entity.IndexableCrossEntityReference;
61 import org.onap.aai.sparky.sync.entity.MergableEntity;
62 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
63 import org.onap.aai.sparky.sync.enumeration.OperationState;
64 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
65 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
66 import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
67 import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
68 import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
69 import org.onap.aai.sparky.util.NodeUtils;
72 import com.fasterxml.jackson.core.JsonProcessingException;
73 import com.fasterxml.jackson.databind.JsonNode;
74 import com.fasterxml.jackson.databind.ObjectReader;
75 import com.fasterxml.jackson.databind.node.ArrayNode;
78 * The Class CrossEntityReferenceSynchronizer.
80 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
81 implements IndexSynchronizer {
84 * The Class RetryCrossEntitySyncContainer.
86 private class RetryCrossEntitySyncContainer {
87 NetworkTransaction txn;
88 IndexableCrossEntityReference icer;
91 * Instantiates a new retry cross entity sync container.
94 * @param icer the icer
96 public RetryCrossEntitySyncContainer(NetworkTransaction txn,
97 IndexableCrossEntityReference icer) {
102 public NetworkTransaction getNetworkTransaction() {
106 public IndexableCrossEntityReference getIndexableCrossEntityReference() {
111 private static final Logger LOG =
112 LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
114 private static final String SERVICE_INSTANCE = "service-instance";
116 private Deque<SelfLinkDescriptor> selflinks;
117 private Deque<RetryCrossEntitySyncContainer> retryQueue;
118 private Map<String, Integer> retryLimitTracker;
119 private boolean isAllWorkEnumerated;
120 protected ExecutorService esPutExecutor;
124 * Instantiates a new cross entity reference synchronizer.
126 * @param indexName the index name
127 * @throws Exception the exception
129 public CrossEntityReferenceSynchronizer(ElasticSearchSchemaConfig schemaConfig,
130 int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
131 NetworkStatisticsConfig esStatConfig) throws Exception {
132 super(LOG, "CERS", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
133 aaiStatConfig, esStatConfig);
134 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
135 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
136 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
137 this.synchronizerName = "Cross Reference Entity Synchronizer";
138 this.isAllWorkEnumerated = false;
139 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
140 this.aaiEntityStats.intializeEntityCounters(
141 CrossEntityReferenceLookup.getInstance().getCrossReferenceEntityDescriptors().keySet());
143 this.esEntityStats.intializeEntityCounters(
144 CrossEntityReferenceLookup.getInstance().getCrossReferenceEntityDescriptors().keySet());
145 this.syncDurationInMs = -1;
151 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
154 public OperationState doSync() {
155 this.syncDurationInMs = -1;
156 String txnID = NodeUtils.getRandomTxnId();
157 MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
160 syncStartedTimeStampInMs = System.currentTimeMillis();
162 return OperationState.OK;
166 public SynchronizerState getState() {
168 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
171 return SynchronizerState.IDLE;
177 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
180 public String getStatReport(boolean showFinalReport) {
181 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
182 return getStatReport(syncDurationInMs, showFinalReport);
188 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
191 public void shutdown() {
192 this.shutdownExecutors();
196 protected boolean isSyncDone() {
197 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
199 if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
209 * @return the operation state
211 private OperationState launchSyncFlow() {
212 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
213 Map<String, CrossEntityReferenceDescriptor> descriptorMap =
214 CrossEntityReferenceLookup.getInstance().getCrossReferenceEntityDescriptors();
216 if (descriptorMap.isEmpty()) {
217 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
219 return OperationState.ERROR;
222 Collection<String> syncTypes = descriptorMap.keySet();
227 * launch a parallel async thread to process the documents for each entity-type (to max the of
228 * the configured executor anyway)
231 aaiWorkOnHand.set(syncTypes.size());
233 for (String key : syncTypes) {
235 supplyAsync(new Supplier<Void>() {
239 MDC.setContextMap(contextMap);
240 OperationResult typeLinksResult = null;
242 typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
243 aaiWorkOnHand.decrementAndGet();
244 processEntityTypeSelfLinks(typeLinksResult);
245 } catch (Exception exc) {
246 // TODO -> LOG, what should be logged here?
252 }, aaiExecutor).whenComplete((result, error) -> {
254 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
259 while (aaiWorkOnHand.get() != 0) {
261 if (LOG.isDebugEnabled()) {
262 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
268 aaiWorkOnHand.set(selflinks.size());
269 isAllWorkEnumerated = true;
272 while (!isSyncDone()) {
278 * Make sure we don't hang on to retries that failed which could cause issues during future
281 retryLimitTracker.clear();
283 } catch (Exception exc) {
284 // TODO -> LOG, waht should be logged here?
287 return OperationState.OK;
293 private void performSync() {
294 while (selflinks.peek() != null) {
296 SelfLinkDescriptor linkDescriptor = selflinks.poll();
297 aaiWorkOnHand.decrementAndGet();
299 CrossEntityReferenceDescriptor descriptor = null;
301 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
303 descriptor = CrossEntityReferenceLookup.getInstance().getCrossReferenceEntityDescriptors()
304 .get(linkDescriptor.getEntityType());
306 if (descriptor == null) {
307 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
308 // go to next element in iterator
312 if (descriptor.hasCrossEntityReferences()) {
314 NetworkTransaction txn = new NetworkTransaction();
315 txn.setDescriptor(descriptor);
316 txn.setLink(linkDescriptor.getSelfLink());
317 txn.setQueryParameters(linkDescriptor.getDepthModifier());
318 txn.setOperationType(HttpMethod.GET);
319 txn.setEntityType(linkDescriptor.getEntityType());
321 aaiWorkOnHand.incrementAndGet();
323 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
324 .whenComplete((result, error) -> {
326 aaiWorkOnHand.decrementAndGet();
329 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
331 if (result == null) {
332 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
334 updateActiveInventoryCounters(result);
335 fetchDocumentForUpsert(result);
345 * Process entity type self links.
347 * @param operationResult the operation result
349 private void processEntityTypeSelfLinks(OperationResult operationResult) {
351 JsonNode rootNode = null;
353 final String jsonResult = operationResult.getResult();
355 if (jsonResult != null && jsonResult.length() > 0) {
358 rootNode = mapper.readTree(jsonResult);
359 } catch (IOException exc) {
360 // TODO // TODO -> LOG, waht should be logged here?
363 JsonNode resultData = rootNode.get("result-data");
364 ArrayNode resultDataArrayNode = null;
366 CrossEntityReferenceLookup cerLookup = CrossEntityReferenceLookup.getInstance();
368 if (resultData.isArray()) {
369 resultDataArrayNode = (ArrayNode) resultData;
371 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
372 JsonNode element = null;
374 while (elementIterator.hasNext()) {
375 element = elementIterator.next();
377 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
378 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
380 CrossEntityReferenceDescriptor descriptor = null;
382 if (resourceType != null && resourceLink != null) {
383 descriptor = cerLookup.getCrossReferenceEntityDescriptors().get(resourceType);
385 if (descriptor == null) {
386 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
387 // go to next element in iterator
390 if (descriptor.hasCrossEntityReferences()) {
391 selflinks.add(new SelfLinkDescriptor(resourceLink,
392 SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
403 * By providing the entity type and a json node for the entity, determine the primary key name(s)
404 * + primary key value(s) sufficient to build an entity query string of the following format:
406 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
408 * @return - a composite string in the above format or null
410 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
412 OxmEntityDescriptor entityDescriptor =
413 OxmEntityLookup.getInstance().getEntityDescriptors().get(entityType);
415 String queryString = null;
417 if (entityDescriptor != null) {
419 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
420 final List<String> keyValues = new ArrayList<String>();
421 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
423 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames, "/") + ":"
424 + NodeUtils.concatArray(keyValues);
434 * Fetch document for upsert.
438 private void fetchDocumentForUpsert(NetworkTransaction txn) {
440 if (!txn.getOperationResult().wasSuccessful()) {
441 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
445 CrossEntityReferenceDescriptor cerDescriptor = CrossEntityReferenceLookup.getInstance()
446 .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
448 if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
450 final String jsonResult = txn.getOperationResult().getResult();
452 if (jsonResult != null && jsonResult.length() > 0) {
455 * Here's what we are going to do:
457 * <li>Extract primary key name and value from the parent type.
458 * <li>Extract the primary key and value from the nested child instance.
459 * <li>Build a generic query to discover the self-link for the nested-child-instance using
461 * <li>Set the self-link on the child.
462 * <li>Generate the id that will allow the elastic-search upsert to work.
463 * <li>Rinse and repeat.
466 CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
468 if (cerDefinition != null) {
469 JsonNode convertedNode = null;
472 NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
474 final String parentEntityQueryString =
475 determineEntityQueryString(txn.getEntityType(), convertedNode);
477 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
479 NodeUtils.extractFieldValuesFromObject(convertedNode,
480 cerDefinition.getReferenceAttributes(), extractedParentEntityAttributeValues);
482 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
483 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
484 nestedTargetEntityInstances);
486 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
488 if (cerDescriptor != null) {
490 String childEntityType = cerDefinition.getTargetEntityType();
492 List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeNames();
494 List<String> childKeyValues = new ArrayList<String>();
495 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames,
498 String childEntityQueryKeyString =
499 childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames, "/") + ":"
500 + NodeUtils.concatArray(childKeyValues);
503 * Build generic-query to query child instance self-link from AAI
505 List<String> orderedQueryKeyParams = new ArrayList<String>();
508 * At present, there is an issue with resolving the self-link using the
509 * generic-query with nothing more than the service-instance identifier and the
510 * service-subscription. There is another level of detail we don't have access to
511 * unless we parse it out of the service-subscription self-link, which is a coupling
512 * I would like to avoid. Fortunately, there is a workaround, but only for
513 * service-instances, which is presently our only use-case for the
514 * cross-entity-reference in R1707. Going forwards hopefully there will be other
515 * ways to resolve a child self-link using parental embedded meta data that we don't
518 * The work-around with the service-instance entity-type is that it's possible to
519 * request the self-link using only the service-instance-id because of a historical
520 * AAI functional query requirement that it be possible to query a service-instance
521 * only by it's service-instance-id. This entity type is the only one in the system
522 * that can be queried this way which makes it a very limited workaround, but good
523 * enough for the current release.
526 if (SERVICE_INSTANCE.equals(childEntityType)) {
527 orderedQueryKeyParams.clear();
528 orderedQueryKeyParams.add(childEntityQueryKeyString);
530 orderedQueryKeyParams.add(parentEntityQueryString);
531 orderedQueryKeyParams.add(childEntityQueryKeyString);
534 String genericQueryStr = null;
537 aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
539 if (genericQueryStr != null) {
540 aaiWorkOnHand.incrementAndGet();
542 OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
543 genericQueryStr, "application/json", aaiAdapter.getNumRequestRetries());
545 aaiWorkOnHand.decrementAndGet();
547 if (aaiQueryResult != null && aaiQueryResult.wasSuccessful()) {
549 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
550 JsonNode genericQueryResult = null;
553 NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
555 if (genericQueryResult != null) {
557 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link",
560 String selfLink = null;
562 if (entityLinks.size() != 1) {
564 * an ambiguity exists where we can't reliably determine the self link,
565 * this should be a permanent error
567 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY,
568 String.valueOf(entityLinks.size()));
570 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
572 SearchableEntityLookup searchableEntityLookup =
573 SearchableEntityLookup.getInstance();
575 SearchableOxmEntityDescriptor searchableDescriptor =
576 searchableEntityLookup.getSearchableEntityDescriptors()
577 .get(txn.getEntityType());
579 if (searchableDescriptor != null
580 && searchableDescriptor.getSearchableAttributes().size() > 0) {
582 IndexableCrossEntityReference icer =
583 getPopulatedDocument(targetEntityInstance, cerDescriptor);
585 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
586 icer.addCrossEntityReferenceValue(
587 parentCrossEntityReferenceAttributeValue);
590 icer.setLink(ActiveInventoryConfig.extractResourcePath(selfLink));
596 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
597 } catch (Exception exc) {
598 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
599 exc.getLocalizedMessage());
603 NetworkTransaction n2 = new NetworkTransaction();
605 n2.setEntityType(txn.getEntityType());
606 n2.setDescriptor(txn.getDescriptor());
607 n2.setOperationType(HttpMethod.GET);
609 esWorkOnHand.incrementAndGet();
612 new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
613 esExecutor).whenComplete((result, error) -> {
615 esWorkOnHand.decrementAndGet();
618 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
619 error.getLocalizedMessage());
621 updateElasticSearchCounters(result);
622 performDocumentUpsert(result, icer);
629 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
632 } catch (Exception exc) {
633 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(),
634 exc.getLocalizedMessage());
638 String message = "Entity sync failed because AAI query failed with error "
639 + aaiQueryResult.getResult();
640 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
645 "Entity Sync failed because generic query str could not be determined.";
646 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
648 } catch (Exception exc) {
650 "Failed to sync entity because generation of generic query failed with error = "
652 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
658 } catch (IOException ioe) {
659 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
666 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
671 * Perform document upsert.
673 * @param esGetResult the es get result
674 * @param icer the icer
676 protected void performDocumentUpsert(NetworkTransaction esGetResult,
677 IndexableCrossEntityReference icer) {
681 * As part of the response processing we need to do the following:
682 * <li>1. Extract the version (if present), it will be the ETAG when we use the
683 * Search-Abstraction-Service
684 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
686 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
687 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
693 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
694 } catch (Exception exc) {
695 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
699 boolean wasEntryDiscovered = false;
700 String versionNumber = null;
701 if (esGetResult.getOperationResult().getResultCode() == 404) {
702 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
703 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
704 wasEntryDiscovered = true;
706 versionNumber = NodeUtils.extractFieldValueFromObject(
707 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
709 } catch (IOException exc) {
710 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
711 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
716 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
719 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
720 String.valueOf(esGetResult.getOperationResult().getResultCode()));
725 String jsonPayload = null;
726 if (wasEntryDiscovered) {
728 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
729 NodeUtils.extractObjectsByKey(
730 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
731 "_source", sourceObject);
733 if (!sourceObject.isEmpty()) {
734 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
735 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
736 ObjectReader updater = mapper.readerForUpdating(me);
737 MergableEntity merged = updater.readValue(icer.getAsJson());
738 jsonPayload = mapper.writeValueAsString(merged);
740 } catch (IOException exc) {
741 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
742 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
746 jsonPayload = icer.getAsJson();
749 if (wasEntryDiscovered) {
750 if (versionNumber != null && jsonPayload != null) {
752 String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(
753 getIndexName(), ElasticSearchConfig.getConfig().getType(), icer.getId(),
754 versionNumber, jsonPayload);
756 NetworkTransaction transactionTracker = new NetworkTransaction();
757 transactionTracker.setEntityType(esGetResult.getEntityType());
758 transactionTracker.setDescriptor(esGetResult.getDescriptor());
759 transactionTracker.setOperationType(HttpMethod.PUT);
761 esWorkOnHand.incrementAndGet();
762 supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
763 requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
764 .whenComplete((result, error) -> {
766 esWorkOnHand.decrementAndGet();
769 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
771 updateElasticSearchCounters(result);
772 processStoreDocumentResult(result, esGetResult, icer);
778 if (link != null && jsonPayload != null) {
780 NetworkTransaction updateElasticTxn = new NetworkTransaction();
781 updateElasticTxn.setLink(link);
782 updateElasticTxn.setEntityType(esGetResult.getEntityType());
783 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
784 updateElasticTxn.setOperationType(HttpMethod.PUT);
786 esWorkOnHand.incrementAndGet();
788 new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
789 esPutExecutor).whenComplete((result, error) -> {
791 esWorkOnHand.decrementAndGet();
794 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
796 updateElasticSearchCounters(result);
797 processStoreDocumentResult(result, esGetResult, icer);
802 } catch (Exception exc) {
803 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
808 * Process store document result.
810 * @param esPutResult the es put result
811 * @param esGetResult the es get result
812 * @param icer the icer
814 private void processStoreDocumentResult(NetworkTransaction esPutResult,
815 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
817 OperationResult or = esPutResult.getOperationResult();
819 if (!or.wasSuccessful()) {
820 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
822 if (shouldAllowRetry(icer.getId())) {
824 esWorkOnHand.incrementAndGet();
826 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
827 retryQueue.push(rsc);
829 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
832 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
839 * Perform retry sync.
841 private void performRetrySync() {
842 while (retryQueue.peek() != null) {
844 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
847 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
848 NetworkTransaction txn = rsc.getNetworkTransaction();
852 // In this retry flow the icer object has already
853 // derived its fields
854 link = getElasticFullUrl("/" + icer.getId(), getIndexName());
855 } catch (Exception exc) {
856 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
860 NetworkTransaction retryTransaction = new NetworkTransaction();
861 retryTransaction.setLink(link);
862 retryTransaction.setEntityType(txn.getEntityType());
863 retryTransaction.setDescriptor(txn.getDescriptor());
864 retryTransaction.setOperationType(HttpMethod.GET);
867 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
868 * that for this request already when queuing the failed PUT!
871 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
872 esExecutor).whenComplete((result, error) -> {
874 esWorkOnHand.decrementAndGet();
877 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
879 updateElasticSearchCounters(result);
880 performDocumentUpsert(result, icer);
890 * Should allow retry.
893 * @return true, if successful
895 private boolean shouldAllowRetry(String id) {
896 boolean isRetryAllowed = true;
897 if (retryLimitTracker.get(id) != null) {
898 Integer currentCount = retryLimitTracker.get(id);
899 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
900 isRetryAllowed = false;
901 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
903 Integer newCount = new Integer(currentCount.intValue() + 1);
904 retryLimitTracker.put(id, newCount);
908 Integer firstRetryCount = new Integer(1);
909 retryLimitTracker.put(id, firstRetryCount);
912 return isRetryAllowed;
916 * Gets the populated document.
918 * @param entityNode the entity node
919 * @param resultDescriptor the result descriptor
920 * @return the populated document
921 * @throws JsonProcessingException the json processing exception
922 * @throws IOException Signals that an I/O exception has occurred.
924 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
925 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
927 IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
929 icer.setEntityType(resultDescriptor.getEntityName());
931 List<String> primaryKeyValues = new ArrayList<String>();
932 String pkeyValue = null;
934 for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
935 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
936 if (pkeyValue != null) {
937 primaryKeyValues.add(pkeyValue);
939 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
943 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
944 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);