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.ActiveInventoryAdapter;
51 import org.onap.aai.sparky.dal.NetworkTransaction;
52 import org.onap.aai.sparky.dal.rest.HttpMethod;
53 import org.onap.aai.sparky.logging.AaiUiMsgs;
54 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
55 import org.onap.aai.sparky.sync.IndexSynchronizer;
56 import org.onap.aai.sparky.sync.SynchronizerConstants;
57 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
58 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
59 import org.onap.aai.sparky.sync.entity.IndexableCrossEntityReference;
60 import org.onap.aai.sparky.sync.entity.MergableEntity;
61 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
62 import org.onap.aai.sparky.sync.enumeration.OperationState;
63 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
64 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
65 import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
66 import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
67 import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
68 import org.onap.aai.sparky.util.NodeUtils;
71 import com.fasterxml.jackson.core.JsonProcessingException;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectReader;
74 import com.fasterxml.jackson.databind.node.ArrayNode;
77 * The Class CrossEntityReferenceSynchronizer.
79 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
80 implements IndexSynchronizer {
83 * The Class RetryCrossEntitySyncContainer.
85 private class RetryCrossEntitySyncContainer {
86 NetworkTransaction txn;
87 IndexableCrossEntityReference icer;
90 * Instantiates a new retry cross entity sync container.
93 * @param icer the icer
95 public RetryCrossEntitySyncContainer(NetworkTransaction txn,
96 IndexableCrossEntityReference icer) {
101 public NetworkTransaction getNetworkTransaction() {
105 public IndexableCrossEntityReference getIndexableCrossEntityReference() {
110 private static final Logger LOG =
111 LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
113 private static final String SERVICE_INSTANCE = "service-instance";
115 private Deque<SelfLinkDescriptor> selflinks;
116 private Deque<RetryCrossEntitySyncContainer> retryQueue;
117 private Map<String, Integer> retryLimitTracker;
118 private boolean isAllWorkEnumerated;
119 protected ExecutorService esPutExecutor;
120 private CrossEntityReferenceLookup crossEntityReferenceLookup;
121 private OxmEntityLookup oxmEntityLookup;
122 private SearchableEntityLookup searchableEntityLookup;
126 * Instantiates a new cross entity reference synchronizer.
128 * @param indexName the index name
129 * @throws Exception the exception
131 public CrossEntityReferenceSynchronizer(ElasticSearchSchemaConfig schemaConfig,
132 int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
133 NetworkStatisticsConfig esStatConfig, CrossEntityReferenceLookup crossEntityReferenceLookup,
134 OxmEntityLookup oxmEntityLookup, SearchableEntityLookup searchableEntityLookup) throws Exception {
135 super(LOG, "CERS", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
136 aaiStatConfig, esStatConfig);
137 this.crossEntityReferenceLookup = crossEntityReferenceLookup;
138 this.oxmEntityLookup = oxmEntityLookup;
139 this.searchableEntityLookup = searchableEntityLookup;
140 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
141 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
142 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
143 this.synchronizerName = "Cross Reference Entity Synchronizer";
144 this.isAllWorkEnumerated = false;
145 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
146 this.aaiEntityStats.intializeEntityCounters(
147 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
149 this.esEntityStats.intializeEntityCounters(
150 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
151 this.syncDurationInMs = -1;
155 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
158 public OperationState doSync() {
159 this.syncDurationInMs = -1;
160 String txnID = NodeUtils.getRandomTxnId();
161 MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
164 syncStartedTimeStampInMs = System.currentTimeMillis();
166 return OperationState.OK;
170 public SynchronizerState getState() {
172 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
175 return SynchronizerState.IDLE;
179 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
182 public String getStatReport(boolean showFinalReport) {
183 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
184 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.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 LOG.error(AaiUiMsgs.ERROR_GENERIC,
247 "An error occurred processing entity selflinks. Error: " + exc.getMessage());
253 }, aaiExecutor).whenComplete((result, error) -> {
255 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
260 while (aaiWorkOnHand.get() != 0) {
262 if (LOG.isDebugEnabled()) {
263 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
269 aaiWorkOnHand.set(selflinks.size());
270 isAllWorkEnumerated = true;
273 while (!isSyncDone()) {
279 * Make sure we don't hang on to retries that failed which could cause issues during future
282 retryLimitTracker.clear();
284 } catch (Exception exc) {
285 LOG.error(AaiUiMsgs.ERROR_GENERIC,
286 "An error occurred during entity synchronization. Error: " + exc.getMessage());
290 return OperationState.OK;
296 private void performSync() {
297 while (selflinks.peek() != null) {
299 SelfLinkDescriptor linkDescriptor = selflinks.poll();
300 aaiWorkOnHand.decrementAndGet();
302 CrossEntityReferenceDescriptor descriptor = null;
304 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
306 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors()
307 .get(linkDescriptor.getEntityType());
309 if (descriptor == null) {
310 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
311 // go to next element in iterator
315 if (descriptor.hasCrossEntityReferences()) {
317 NetworkTransaction txn = new NetworkTransaction();
318 txn.setDescriptor(descriptor);
319 txn.setLink(linkDescriptor.getSelfLink());
320 txn.setQueryParameters(linkDescriptor.getDepthModifier());
321 txn.setOperationType(HttpMethod.GET);
322 txn.setEntityType(linkDescriptor.getEntityType());
324 aaiWorkOnHand.incrementAndGet();
326 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
327 .whenComplete((result, error) -> {
329 aaiWorkOnHand.decrementAndGet();
332 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
334 if (result == null) {
335 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
337 updateActiveInventoryCounters(result);
338 fetchDocumentForUpsert(result);
348 * Process entity type self links.
350 * @param operationResult the operation result
352 private void processEntityTypeSelfLinks(OperationResult operationResult) {
354 JsonNode rootNode = null;
356 final String jsonResult = operationResult.getResult();
358 if (jsonResult != null && jsonResult.length() > 0) {
361 rootNode = mapper.readTree(jsonResult);
362 } catch (IOException exc) {
363 // TODO // TODO -> LOG, waht should be logged here?
366 JsonNode resultData = rootNode.get("result-data");
367 ArrayNode resultDataArrayNode = null;
369 if (resultData.isArray()) {
370 resultDataArrayNode = (ArrayNode) resultData;
372 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
373 JsonNode element = null;
375 while (elementIterator.hasNext()) {
376 element = elementIterator.next();
378 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
379 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
381 CrossEntityReferenceDescriptor descriptor = null;
383 if (resourceType != null && resourceLink != null) {
384 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);
386 if (descriptor == null) {
387 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
388 // go to next element in iterator
391 if (descriptor.hasCrossEntityReferences()) {
392 selflinks.add(new SelfLinkDescriptor(
393 resourceLink,SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
404 * By providing the entity type and a json node for the entity, determine the
405 * primary key name(s) + primary key value(s) sufficient to build an entity query string
406 * of the following format:
408 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
410 * @return - a composite string in the above format or null
412 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
414 OxmEntityDescriptor entityDescriptor =
415 oxmEntityLookup.getEntityDescriptors().get(entityType);
417 String queryString = null;
419 if ( entityDescriptor != null ) {
421 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
422 final List<String> keyValues = new ArrayList<String>();
423 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
425 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
435 * Fetch document for upsert.
439 private void fetchDocumentForUpsert(NetworkTransaction txn) {
441 if (!txn.getOperationResult().wasSuccessful()) {
442 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
446 CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
447 .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
449 if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
451 final String jsonResult = txn.getOperationResult().getResult();
453 if (jsonResult != null && jsonResult.length() > 0) {
456 * Here's what we are going to do:
458 * <li>Extract primary key name and value from the parent type.
459 * <li>Extract the primary key and value from the nested child instance.
460 * <li>Build a generic query to discover the self-link for the nested-child-instance using
462 * <li>Set the self-link on the child.
463 * <li>Generate the id that will allow the elastic-search upsert to work.
464 * <li>Rinse and repeat.
467 CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
469 if (cerDefinition != null) {
470 JsonNode convertedNode = null;
472 convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
474 final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
476 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
478 NodeUtils.extractFieldValuesFromObject(convertedNode,
479 cerDefinition.getReferenceAttributes(),
480 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();
491 OxmEntityDescriptor childDesciptor = oxmEntityLookup.getEntityDescriptors().get(childEntityType);
493 List<String> childPrimaryKeyNames = null;
495 if (childDesciptor != null) {
496 childPrimaryKeyNames = childDesciptor.getPrimaryKeyAttributeNames();
498 childPrimaryKeyNames = new ArrayList<String>();
501 List<String> childKeyValues = new ArrayList<String>();
502 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
504 String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
507 * Build generic-query to query child instance self-link from AAI
509 List<String> orderedQueryKeyParams = new ArrayList<String>();
512 * At present, there is an issue with resolving the self-link using the
513 * generic-query with nothing more than the service-instance identifier and the
514 * service-subscription. There is another level of detail we don't have access to
515 * unless we parse it out of the service-subscription self-link, which is a
516 * coupling I would like to avoid. Fortunately, there is a workaround, but only
517 * for service-instances, which is presently our only use-case for the
518 * cross-entity-reference in R1707. Going forwards hopefully there will be other
519 * ways to resolve a child self-link using parental embedded meta data that we
520 * don't currently have.
522 * The work-around with the service-instance entity-type is that it's possible to
523 * request the self-link using only the service-instance-id because of a
524 * historical AAI functional query requirement that it be possible to query a
525 * service-instance only by it's service-instance-id. This entity type is the only
526 * one in the system that can be queried this way which makes it a very limited
527 * workaround, but good enough for the current release.
530 if (SERVICE_INSTANCE.equals(childEntityType)) {
531 orderedQueryKeyParams.clear();
532 orderedQueryKeyParams.add(childEntityQueryKeyString);
534 orderedQueryKeyParams.add(parentEntityQueryString);
535 orderedQueryKeyParams.add(childEntityQueryKeyString);
538 String genericQueryStr = null;
540 genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
542 if (genericQueryStr != null) {
543 aaiWorkOnHand.incrementAndGet();
545 OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
546 genericQueryStr, "application/json",
547 aaiAdapter.getEndpointConfig().getNumRequestRetries());
549 aaiWorkOnHand.decrementAndGet();
551 if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
553 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
554 JsonNode genericQueryResult = null;
556 genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
558 if ( genericQueryResult != null ) {
560 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
562 String selfLink = null;
564 if (entityLinks.size() != 1) {
566 * an ambiguity exists where we can't reliably determine the self
567 * link, this should be a permanent error
569 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
571 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
574 IndexableCrossEntityReference icer =
575 getPopulatedDocument(targetEntityInstance, cerDescriptor);
577 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
578 icer.addCrossEntityReferenceValue(
579 parentCrossEntityReferenceAttributeValue);
582 icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));
588 link = elasticSearchAdapter
589 .buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
590 } catch (Exception exc) {
591 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
592 exc.getLocalizedMessage());
596 NetworkTransaction n2 = new NetworkTransaction();
598 n2.setEntityType(txn.getEntityType());
599 n2.setDescriptor(txn.getDescriptor());
600 n2.setOperationType(HttpMethod.GET);
602 esWorkOnHand.incrementAndGet();
605 new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
606 esExecutor).whenComplete((result, error) -> {
608 esWorkOnHand.decrementAndGet();
611 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
612 error.getLocalizedMessage());
614 updateElasticSearchCounters(result);
615 performDocumentUpsert(result, icer);
622 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
625 } catch (Exception exc) {
626 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
630 String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult();
631 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
635 String message = "Entity Sync failed because generic query str could not be determined.";
636 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
638 } catch (Exception exc) {
639 String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
640 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
646 } catch (IOException ioe) {
647 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
654 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
659 * Perform document upsert.
661 * @param esGetResult the es get result
662 * @param icer the icer
664 protected void performDocumentUpsert(NetworkTransaction esGetResult,
665 IndexableCrossEntityReference icer) {
669 * As part of the response processing we need to do the following:
670 * <li>1. Extract the version (if present), it will be the ETAG when we use the
671 * Search-Abstraction-Service
672 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
674 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
675 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
681 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
682 } catch (Exception exc) {
683 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
687 boolean wasEntryDiscovered = false;
688 String versionNumber = null;
689 if (esGetResult.getOperationResult().getResultCode() == 404) {
690 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
691 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
692 wasEntryDiscovered = true;
694 versionNumber = NodeUtils.extractFieldValueFromObject(
695 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
697 } catch (IOException exc) {
698 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
699 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
704 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
707 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
708 String.valueOf(esGetResult.getOperationResult().getResultCode()));
713 String jsonPayload = null;
714 if (wasEntryDiscovered) {
716 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
717 NodeUtils.extractObjectsByKey(
718 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
719 "_source", sourceObject);
721 if (!sourceObject.isEmpty()) {
722 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
723 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
724 ObjectReader updater = mapper.readerForUpdating(me);
725 MergableEntity merged = updater.readValue(icer.getAsJson());
726 jsonPayload = mapper.writeValueAsString(merged);
728 } catch (IOException exc) {
729 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
730 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
734 jsonPayload = icer.getAsJson();
737 if (wasEntryDiscovered) {
738 if (versionNumber != null && jsonPayload != null) {
740 String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
741 "default", icer.getId(), versionNumber, jsonPayload);
743 NetworkTransaction transactionTracker = new NetworkTransaction();
744 transactionTracker.setEntityType(esGetResult.getEntityType());
745 transactionTracker.setDescriptor(esGetResult.getDescriptor());
746 transactionTracker.setOperationType(HttpMethod.PUT);
748 esWorkOnHand.incrementAndGet();
749 supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
750 requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
751 .whenComplete((result, error) -> {
753 esWorkOnHand.decrementAndGet();
756 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
758 updateElasticSearchCounters(result);
759 processStoreDocumentResult(result, esGetResult, icer);
765 if (link != null && jsonPayload != null) {
767 NetworkTransaction updateElasticTxn = new NetworkTransaction();
768 updateElasticTxn.setLink(link);
769 updateElasticTxn.setEntityType(esGetResult.getEntityType());
770 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
771 updateElasticTxn.setOperationType(HttpMethod.PUT);
773 esWorkOnHand.incrementAndGet();
774 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
775 esPutExecutor).whenComplete((result, error) -> {
777 esWorkOnHand.decrementAndGet();
780 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
782 updateElasticSearchCounters(result);
783 processStoreDocumentResult(result, esGetResult, icer);
788 } catch (Exception exc) {
789 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
794 * Process store document result.
796 * @param esPutResult the es put result
797 * @param esGetResult the es get result
798 * @param icer the icer
800 private void processStoreDocumentResult(NetworkTransaction esPutResult,
801 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
803 OperationResult or = esPutResult.getOperationResult();
805 if (!or.wasSuccessful()) {
806 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
808 if (shouldAllowRetry(icer.getId())) {
810 esWorkOnHand.incrementAndGet();
812 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
813 retryQueue.push(rsc);
815 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
818 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
825 * Perform retry sync.
827 private void performRetrySync() {
828 while (retryQueue.peek() != null) {
830 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
833 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
834 NetworkTransaction txn = rsc.getNetworkTransaction();
838 // In this retry flow the icer object has already
839 // derived its fields
840 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
841 } catch (Exception exc) {
842 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
846 NetworkTransaction retryTransaction = new NetworkTransaction();
847 retryTransaction.setLink(link);
848 retryTransaction.setEntityType(txn.getEntityType());
849 retryTransaction.setDescriptor(txn.getDescriptor());
850 retryTransaction.setOperationType(HttpMethod.GET);
853 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
854 * that for this request already when queuing the failed PUT!
857 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
858 esExecutor).whenComplete((result, error) -> {
860 esWorkOnHand.decrementAndGet();
863 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
865 updateElasticSearchCounters(result);
866 performDocumentUpsert(result, icer);
876 * Should allow retry.
879 * @return true, if successful
881 private boolean shouldAllowRetry(String id) {
882 boolean isRetryAllowed = true;
883 if (retryLimitTracker.get(id) != null) {
884 Integer currentCount = retryLimitTracker.get(id);
885 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
886 isRetryAllowed = false;
887 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
889 Integer newCount = new Integer(currentCount.intValue() + 1);
890 retryLimitTracker.put(id, newCount);
894 Integer firstRetryCount = new Integer(1);
895 retryLimitTracker.put(id, firstRetryCount);
898 return isRetryAllowed;
902 * Gets the populated document.
904 * @param entityNode the entity node
905 * @param resultDescriptor the result descriptor
906 * @return the populated document
907 * @throws JsonProcessingException the json processing exception
908 * @throws IOException Signals that an I/O exception has occurred.
910 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
911 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
913 IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
915 icer.setEntityType(resultDescriptor.getEntityName());
917 List<String> primaryKeyValues = new ArrayList<String>();
918 String pkeyValue = null;
920 for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
921 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
922 if (pkeyValue != null) {
923 primaryKeyValues.add(pkeyValue);
925 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
929 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
930 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);