2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 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 package org.onap.aai.sparky.crossentityreference.sync;
23 import static java.util.concurrent.CompletableFuture.supplyAsync;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Deque;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentLinkedDeque;
34 import java.util.concurrent.ExecutorService;
35 import java.util.function.Supplier;
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.cl.mdc.MdcContext;
40 import org.onap.aai.restclient.client.OperationResult;
41 import org.onap.aai.sparky.config.oxm.CrossEntityReference;
42 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceDescriptor;
43 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceLookup;
44 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
45 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
46 import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
47 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
48 import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
49 import org.onap.aai.sparky.dal.NetworkTransaction;
50 import org.onap.aai.sparky.dal.rest.HttpMethod;
51 import org.onap.aai.sparky.logging.AaiUiMsgs;
52 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
53 import org.onap.aai.sparky.sync.IndexSynchronizer;
54 import org.onap.aai.sparky.sync.SynchronizerConstants;
55 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
56 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
57 import org.onap.aai.sparky.sync.entity.IndexableCrossEntityReference;
58 import org.onap.aai.sparky.sync.entity.MergableEntity;
59 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
60 import org.onap.aai.sparky.sync.enumeration.OperationState;
61 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
62 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
63 import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
64 import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
65 import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
66 import org.onap.aai.sparky.util.NodeUtils;
69 import com.fasterxml.jackson.core.JsonProcessingException;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectReader;
72 import com.fasterxml.jackson.databind.node.ArrayNode;
75 * The Class CrossEntityReferenceSynchronizer.
77 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
78 implements IndexSynchronizer {
81 * The Class RetryCrossEntitySyncContainer.
83 private class RetryCrossEntitySyncContainer {
84 NetworkTransaction txn;
85 IndexableCrossEntityReference icer;
88 * Instantiates a new retry cross entity sync container.
91 * @param icer the icer
93 public RetryCrossEntitySyncContainer(NetworkTransaction txn,
94 IndexableCrossEntityReference icer) {
99 public NetworkTransaction getNetworkTransaction() {
103 public IndexableCrossEntityReference getIndexableCrossEntityReference() {
108 private static final Logger LOG =
109 LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
111 private static final String SERVICE_INSTANCE = "service-instance";
113 private Deque<SelfLinkDescriptor> selflinks;
114 private Deque<RetryCrossEntitySyncContainer> retryQueue;
115 private Map<String, Integer> retryLimitTracker;
116 private boolean isAllWorkEnumerated;
117 protected ExecutorService esPutExecutor;
118 private CrossEntityReferenceLookup crossEntityReferenceLookup;
119 private OxmEntityLookup oxmEntityLookup;
120 private SearchableEntityLookup searchableEntityLookup;
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, CrossEntityReferenceLookup crossEntityReferenceLookup,
132 OxmEntityLookup oxmEntityLookup, SearchableEntityLookup searchableEntityLookup) throws Exception {
133 super(LOG, "CERS", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
134 aaiStatConfig, esStatConfig);
135 this.crossEntityReferenceLookup = crossEntityReferenceLookup;
136 this.oxmEntityLookup = oxmEntityLookup;
137 this.searchableEntityLookup = searchableEntityLookup;
138 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
139 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
140 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
141 this.synchronizerName = "Cross Reference Entity Synchronizer";
142 this.isAllWorkEnumerated = false;
143 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
144 this.aaiEntityStats.intializeEntityCounters(
145 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
147 this.esEntityStats.intializeEntityCounters(
148 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
149 this.syncDurationInMs = -1;
153 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
156 public OperationState doSync() {
157 this.syncDurationInMs = -1;
158 String txnID = NodeUtils.getRandomTxnId();
159 MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
162 syncStartedTimeStampInMs = System.currentTimeMillis();
164 return OperationState.OK;
168 public SynchronizerState getState() {
170 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
173 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);
186 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
189 public void shutdown() {
190 this.shutdownExecutors();
194 protected boolean isSyncDone() {
195 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
197 if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
207 * @return the operation state
209 private OperationState launchSyncFlow() {
210 final Map<String,String> contextMap = MDC.getCopyOfContextMap();
211 Map<String, CrossEntityReferenceDescriptor> descriptorMap =
212 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors();
214 if (descriptorMap.isEmpty()) {
215 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
217 return OperationState.ERROR;
220 Collection<String> syncTypes = descriptorMap.keySet();
225 * launch a parallel async thread to process the documents for each entity-type (to max the of
226 * the configured executor anyway)
229 aaiWorkOnHand.set(syncTypes.size());
231 for (String key : syncTypes) {
233 supplyAsync(new Supplier<Void>() {
237 MDC.setContextMap(contextMap);
238 OperationResult typeLinksResult = null;
240 typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
241 aaiWorkOnHand.decrementAndGet();
242 processEntityTypeSelfLinks(typeLinksResult);
243 } catch (Exception exc) {
244 LOG.error(AaiUiMsgs.ERROR_GENERIC,
245 "An error occurred processing entity selflinks. Error: " + exc.getMessage());
251 }, aaiExecutor).whenComplete((result, error) -> {
253 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
258 while (aaiWorkOnHand.get() != 0) {
260 if (LOG.isDebugEnabled()) {
261 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
267 aaiWorkOnHand.set(selflinks.size());
268 isAllWorkEnumerated = true;
271 while (!isSyncDone()) {
277 * Make sure we don't hang on to retries that failed which could cause issues during future
280 retryLimitTracker.clear();
282 } catch (Exception exc) {
283 LOG.error(AaiUiMsgs.ERROR_GENERIC,
284 "An error occurred during entity synchronization. Error: " + exc.getMessage());
288 return OperationState.OK;
294 private void performSync() {
295 while (selflinks.peek() != null) {
297 SelfLinkDescriptor linkDescriptor = selflinks.poll();
298 aaiWorkOnHand.decrementAndGet();
300 CrossEntityReferenceDescriptor descriptor = null;
302 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
304 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors()
305 .get(linkDescriptor.getEntityType());
307 if (descriptor == null) {
308 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
309 // go to next element in iterator
313 if (descriptor.hasCrossEntityReferences()) {
315 NetworkTransaction txn = new NetworkTransaction();
316 txn.setDescriptor(descriptor);
317 txn.setLink(linkDescriptor.getSelfLink());
318 txn.setQueryParameters(linkDescriptor.getDepthModifier());
319 txn.setOperationType(HttpMethod.GET);
320 txn.setEntityType(linkDescriptor.getEntityType());
322 aaiWorkOnHand.incrementAndGet();
324 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
325 .whenComplete((result, error) -> {
327 aaiWorkOnHand.decrementAndGet();
330 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
332 if (result == null) {
333 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
335 updateActiveInventoryCounters(result);
336 fetchDocumentForUpsert(result);
346 * Process entity type self links.
348 * @param operationResult the operation result
350 private void processEntityTypeSelfLinks(OperationResult operationResult) {
352 JsonNode rootNode = null;
354 final String jsonResult = operationResult.getResult();
356 if (jsonResult != null && jsonResult.length() > 0) {
359 rootNode = mapper.readTree(jsonResult);
360 } catch (IOException exc) {
361 // TODO // TODO -> LOG, waht should be logged here?
364 JsonNode resultData = rootNode.get("result-data");
365 ArrayNode resultDataArrayNode = null;
367 if (resultData.isArray()) {
368 resultDataArrayNode = (ArrayNode) resultData;
370 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
371 JsonNode element = null;
373 while (elementIterator.hasNext()) {
374 element = elementIterator.next();
376 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
377 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
379 CrossEntityReferenceDescriptor descriptor = null;
381 if (resourceType != null && resourceLink != null) {
382 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);
384 if (descriptor == null) {
385 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
386 // go to next element in iterator
389 if (descriptor.hasCrossEntityReferences()) {
390 selflinks.add(new SelfLinkDescriptor(
391 resourceLink,SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
402 * By providing the entity type and a json node for the entity, determine the
403 * primary key name(s) + primary key value(s) sufficient to build an entity query string
404 * 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.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,"/") + ":" + NodeUtils.concatArray(keyValues);
433 * Fetch document for upsert.
437 private void fetchDocumentForUpsert(NetworkTransaction txn) {
439 if (!txn.getOperationResult().wasSuccessful()) {
440 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
444 CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
445 .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
447 if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
449 final String jsonResult = txn.getOperationResult().getResult();
451 if (jsonResult != null && jsonResult.length() > 0) {
454 * Here's what we are going to do:
456 * <li>Extract primary key name and value from the parent type.
457 * <li>Extract the primary key and value from the nested child instance.
458 * <li>Build a generic query to discover the self-link for the nested-child-instance using
460 * <li>Set the self-link on the child.
461 * <li>Generate the id that will allow the elastic-search upsert to work.
462 * <li>Rinse and repeat.
465 CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
467 if (cerDefinition != null) {
468 JsonNode convertedNode = null;
470 convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
472 final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
474 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
476 NodeUtils.extractFieldValuesFromObject(convertedNode,
477 cerDefinition.getReferenceAttributes(),
478 extractedParentEntityAttributeValues);
480 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
481 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
482 nestedTargetEntityInstances);
484 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
486 if (cerDescriptor != null) {
488 String childEntityType = cerDefinition.getTargetEntityType();
489 OxmEntityDescriptor childDesciptor = oxmEntityLookup.getEntityDescriptors().get(childEntityType);
491 List<String> childPrimaryKeyNames = null;
493 if (childDesciptor != null) {
494 childPrimaryKeyNames = childDesciptor.getPrimaryKeyAttributeNames();
496 childPrimaryKeyNames = new ArrayList<String>();
499 List<String> childKeyValues = new ArrayList<String>();
500 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
502 String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
505 * Build generic-query to query child instance self-link from AAI
507 List<String> orderedQueryKeyParams = new ArrayList<String>();
510 * At present, there is an issue with resolving the self-link using the
511 * generic-query with nothing more than the service-instance identifier and the
512 * service-subscription. There is another level of detail we don't have access to
513 * unless we parse it out of the service-subscription self-link, which is a
514 * coupling I would like to avoid. Fortunately, there is a workaround, but only
515 * for service-instances, which is presently our only use-case for the
516 * cross-entity-reference in R1707. Going forwards hopefully there will be other
517 * ways to resolve a child self-link using parental embedded meta data that we
518 * don't currently have.
520 * The work-around with the service-instance entity-type is that it's possible to
521 * request the self-link using only the service-instance-id because of a
522 * historical AAI functional query requirement that it be possible to query a
523 * service-instance only by it's service-instance-id. This entity type is the only
524 * one in the system that can be queried this way which makes it a very limited
525 * workaround, but good enough for the current release.
528 if (SERVICE_INSTANCE.equals(childEntityType)) {
529 orderedQueryKeyParams.clear();
530 orderedQueryKeyParams.add(childEntityQueryKeyString);
532 orderedQueryKeyParams.add(parentEntityQueryString);
533 orderedQueryKeyParams.add(childEntityQueryKeyString);
536 String genericQueryStr = null;
538 genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
540 if (genericQueryStr != null) {
541 aaiWorkOnHand.incrementAndGet();
543 OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
544 genericQueryStr, "application/json",
545 aaiAdapter.getEndpointConfig().getNumRequestRetries());
547 aaiWorkOnHand.decrementAndGet();
549 if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
551 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
552 JsonNode genericQueryResult = null;
554 genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
556 if ( genericQueryResult != null ) {
558 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
560 String selfLink = null;
562 if (entityLinks.size() != 1) {
564 * an ambiguity exists where we can't reliably determine the self
565 * link, this should be a permanent error
567 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
569 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
572 IndexableCrossEntityReference icer =
573 getPopulatedDocument(targetEntityInstance, cerDescriptor);
575 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
576 icer.addCrossEntityReferenceValue(
577 parentCrossEntityReferenceAttributeValue);
580 icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));
586 link = elasticSearchAdapter
587 .buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
588 } catch (Exception exc) {
589 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
590 exc.getLocalizedMessage());
594 NetworkTransaction n2 = new NetworkTransaction();
596 n2.setEntityType(txn.getEntityType());
597 n2.setDescriptor(txn.getDescriptor());
598 n2.setOperationType(HttpMethod.GET);
600 esWorkOnHand.incrementAndGet();
603 new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
604 esExecutor).whenComplete((result, error) -> {
606 esWorkOnHand.decrementAndGet();
609 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
610 error.getLocalizedMessage());
612 updateElasticSearchCounters(result);
613 performDocumentUpsert(result, icer);
620 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
623 } catch (Exception exc) {
624 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
628 String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult();
629 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
633 String message = "Entity Sync failed because generic query str could not be determined.";
634 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
636 } catch (Exception exc) {
637 String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
638 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
644 } catch (IOException ioe) {
645 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
652 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
657 * Perform document upsert.
659 * @param esGetResult the es get result
660 * @param icer the icer
662 protected void performDocumentUpsert(NetworkTransaction esGetResult,
663 IndexableCrossEntityReference icer) {
667 * As part of the response processing we need to do the following:
668 * <li>1. Extract the version (if present), it will be the ETAG when we use the
669 * Search-Abstraction-Service
670 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
672 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
673 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
679 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
680 } catch (Exception exc) {
681 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
685 boolean wasEntryDiscovered = false;
686 String versionNumber = null;
687 if (esGetResult.getOperationResult().getResultCode() == 404) {
688 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
689 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
690 wasEntryDiscovered = true;
692 versionNumber = NodeUtils.extractFieldValueFromObject(
693 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
695 } catch (IOException exc) {
696 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
697 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
702 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
705 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
706 String.valueOf(esGetResult.getOperationResult().getResultCode()));
711 String jsonPayload = null;
712 if (wasEntryDiscovered) {
714 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
715 NodeUtils.extractObjectsByKey(
716 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
717 "_source", sourceObject);
719 if (!sourceObject.isEmpty()) {
720 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
721 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
722 ObjectReader updater = mapper.readerForUpdating(me);
723 MergableEntity merged = updater.readValue(icer.getAsJson());
724 jsonPayload = mapper.writeValueAsString(merged);
726 } catch (IOException exc) {
727 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
728 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
732 jsonPayload = icer.getAsJson();
735 if (wasEntryDiscovered) {
736 if (versionNumber != null && jsonPayload != null) {
738 String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
739 "default", icer.getId(), versionNumber, jsonPayload);
741 NetworkTransaction transactionTracker = new NetworkTransaction();
742 transactionTracker.setEntityType(esGetResult.getEntityType());
743 transactionTracker.setDescriptor(esGetResult.getDescriptor());
744 transactionTracker.setOperationType(HttpMethod.PUT);
746 esWorkOnHand.incrementAndGet();
747 supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
748 requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
749 .whenComplete((result, error) -> {
751 esWorkOnHand.decrementAndGet();
754 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
756 updateElasticSearchCounters(result);
757 processStoreDocumentResult(result, esGetResult, icer);
763 if (link != null && jsonPayload != null) {
765 NetworkTransaction updateElasticTxn = new NetworkTransaction();
766 updateElasticTxn.setLink(link);
767 updateElasticTxn.setEntityType(esGetResult.getEntityType());
768 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
769 updateElasticTxn.setOperationType(HttpMethod.PUT);
771 esWorkOnHand.incrementAndGet();
772 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
773 esPutExecutor).whenComplete((result, error) -> {
775 esWorkOnHand.decrementAndGet();
778 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
780 updateElasticSearchCounters(result);
781 processStoreDocumentResult(result, esGetResult, icer);
786 } catch (Exception exc) {
787 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
792 * Process store document result.
794 * @param esPutResult the es put result
795 * @param esGetResult the es get result
796 * @param icer the icer
798 private void processStoreDocumentResult(NetworkTransaction esPutResult,
799 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
801 OperationResult or = esPutResult.getOperationResult();
803 if (!or.wasSuccessful()) {
804 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
806 if (shouldAllowRetry(icer.getId())) {
808 esWorkOnHand.incrementAndGet();
810 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
811 retryQueue.push(rsc);
813 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
816 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
823 * Perform retry sync.
825 private void performRetrySync() {
826 while (retryQueue.peek() != null) {
828 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
831 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
832 NetworkTransaction txn = rsc.getNetworkTransaction();
836 // In this retry flow the icer object has already
837 // derived its fields
838 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
839 } catch (Exception exc) {
840 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
844 NetworkTransaction retryTransaction = new NetworkTransaction();
845 retryTransaction.setLink(link);
846 retryTransaction.setEntityType(txn.getEntityType());
847 retryTransaction.setDescriptor(txn.getDescriptor());
848 retryTransaction.setOperationType(HttpMethod.GET);
851 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
852 * that for this request already when queuing the failed PUT!
855 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
856 esExecutor).whenComplete((result, error) -> {
858 esWorkOnHand.decrementAndGet();
861 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
863 updateElasticSearchCounters(result);
864 performDocumentUpsert(result, icer);
874 * Should allow retry.
877 * @return true, if successful
879 private boolean shouldAllowRetry(String id) {
880 boolean isRetryAllowed = true;
881 if (retryLimitTracker.get(id) != null) {
882 Integer currentCount = retryLimitTracker.get(id);
883 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
884 isRetryAllowed = false;
885 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
887 Integer newCount = new Integer(currentCount.intValue() + 1);
888 retryLimitTracker.put(id, newCount);
892 Integer firstRetryCount = new Integer(1);
893 retryLimitTracker.put(id, firstRetryCount);
896 return isRetryAllowed;
900 * Gets the populated document.
902 * @param entityNode the entity node
903 * @param resultDescriptor the result descriptor
904 * @return the populated document
905 * @throws JsonProcessingException the json processing exception
906 * @throws IOException Signals that an I/O exception has occurred.
908 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
909 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
911 IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
913 icer.setEntityType(resultDescriptor.getEntityName());
915 List<String> primaryKeyValues = new ArrayList<String>();
916 String pkeyValue = null;
918 for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
919 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
920 if (pkeyValue != null) {
921 primaryKeyValues.add(pkeyValue);
923 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
927 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
928 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);