2 * ============LICENSE_START===================================================
3 * SPARKY (AAI UI service)
4 * ============================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=====================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
25 package org.onap.aai.sparky.crossentityreference.sync;
27 import static java.util.concurrent.CompletableFuture.supplyAsync;
29 import java.io.IOException;
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.onap.aai.cl.api.Logger;
42 import org.onap.aai.cl.eelf.LoggerFactory;
43 import org.onap.aai.cl.mdc.MdcContext;
44 import org.onap.aai.restclient.client.OperationResult;
45 import org.onap.aai.sparky.config.oxm.CrossEntityReference;
46 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceDescriptor;
47 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceLookup;
48 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
49 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
50 import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
51 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
52 import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
53 import org.onap.aai.sparky.dal.NetworkTransaction;
54 import org.onap.aai.sparky.dal.rest.HttpMethod;
55 import org.onap.aai.sparky.logging.AaiUiMsgs;
56 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
57 import org.onap.aai.sparky.sync.IndexSynchronizer;
58 import org.onap.aai.sparky.sync.SynchronizerConstants;
59 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
60 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
61 import org.onap.aai.sparky.sync.entity.IndexableCrossEntityReference;
62 import org.onap.aai.sparky.sync.entity.MergableEntity;
63 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
64 import org.onap.aai.sparky.sync.enumeration.OperationState;
65 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
66 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
67 import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
68 import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
69 import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
70 import org.onap.aai.sparky.util.NodeUtils;
73 import com.fasterxml.jackson.core.JsonProcessingException;
74 import com.fasterxml.jackson.databind.JsonNode;
75 import com.fasterxml.jackson.databind.ObjectReader;
76 import com.fasterxml.jackson.databind.node.ArrayNode;
79 * The Class CrossEntityReferenceSynchronizer.
81 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
82 implements IndexSynchronizer {
85 * The Class RetryCrossEntitySyncContainer.
87 private class RetryCrossEntitySyncContainer {
88 NetworkTransaction txn;
89 IndexableCrossEntityReference icer;
92 * Instantiates a new retry cross entity sync container.
95 * @param icer the icer
97 public RetryCrossEntitySyncContainer(NetworkTransaction txn,
98 IndexableCrossEntityReference icer) {
103 public NetworkTransaction getNetworkTransaction() {
107 public IndexableCrossEntityReference getIndexableCrossEntityReference() {
112 private static final Logger LOG =
113 LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
115 private static final String SERVICE_INSTANCE = "service-instance";
117 private Deque<SelfLinkDescriptor> selflinks;
118 private Deque<RetryCrossEntitySyncContainer> retryQueue;
119 private Map<String, Integer> retryLimitTracker;
120 private boolean isAllWorkEnumerated;
121 protected ExecutorService esPutExecutor;
122 private CrossEntityReferenceLookup crossEntityReferenceLookup;
123 private OxmEntityLookup oxmEntityLookup;
124 private SearchableEntityLookup searchableEntityLookup;
128 * Instantiates a new cross entity reference synchronizer.
130 * @param indexName the index name
131 * @throws Exception the exception
133 public CrossEntityReferenceSynchronizer(ElasticSearchSchemaConfig schemaConfig,
134 int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
135 NetworkStatisticsConfig esStatConfig, CrossEntityReferenceLookup crossEntityReferenceLookup,
136 OxmEntityLookup oxmEntityLookup, SearchableEntityLookup searchableEntityLookup) throws Exception {
137 super(LOG, "CERS", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
138 aaiStatConfig, esStatConfig);
139 this.crossEntityReferenceLookup = crossEntityReferenceLookup;
140 this.oxmEntityLookup = oxmEntityLookup;
141 this.searchableEntityLookup = searchableEntityLookup;
142 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
143 this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
144 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
145 this.synchronizerName = "Cross Reference Entity Synchronizer";
146 this.isAllWorkEnumerated = false;
147 this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
148 this.aaiEntityStats.intializeEntityCounters(
149 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
151 this.esEntityStats.intializeEntityCounters(
152 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
153 this.syncDurationInMs = -1;
157 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
160 public OperationState doSync() {
161 this.syncDurationInMs = -1;
162 String txnID = NodeUtils.getRandomTxnId();
163 MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
166 syncStartedTimeStampInMs = System.currentTimeMillis();
168 return OperationState.OK;
172 public SynchronizerState getState() {
174 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
177 return SynchronizerState.IDLE;
181 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
184 public String getStatReport(boolean showFinalReport) {
185 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
186 return getStatReport(syncDurationInMs, showFinalReport);
190 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
193 public void shutdown() {
194 this.shutdownExecutors();
198 protected boolean isSyncDone() {
199 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
201 if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
211 * @return the operation state
213 private OperationState launchSyncFlow() {
214 final Map<String,String> contextMap = MDC.getCopyOfContextMap();
215 Map<String, CrossEntityReferenceDescriptor> descriptorMap =
216 crossEntityReferenceLookup.getCrossReferenceEntityDescriptors();
218 if (descriptorMap.isEmpty()) {
219 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
221 return OperationState.ERROR;
224 Collection<String> syncTypes = descriptorMap.keySet();
229 * launch a parallel async thread to process the documents for each entity-type (to max the of
230 * the configured executor anyway)
233 aaiWorkOnHand.set(syncTypes.size());
235 for (String key : syncTypes) {
237 supplyAsync(new Supplier<Void>() {
241 MDC.setContextMap(contextMap);
242 OperationResult typeLinksResult = null;
244 typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
245 aaiWorkOnHand.decrementAndGet();
246 processEntityTypeSelfLinks(typeLinksResult);
247 } catch (Exception exc) {
248 LOG.error(AaiUiMsgs.ERROR_GENERIC,
249 "An error occurred processing entity selflinks. Error: " + exc.getMessage());
255 }, aaiExecutor).whenComplete((result, error) -> {
257 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
262 while (aaiWorkOnHand.get() != 0) {
264 if (LOG.isDebugEnabled()) {
265 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
271 aaiWorkOnHand.set(selflinks.size());
272 isAllWorkEnumerated = true;
275 while (!isSyncDone()) {
281 * Make sure we don't hang on to retries that failed which could cause issues during future
284 retryLimitTracker.clear();
286 } catch (Exception exc) {
287 LOG.error(AaiUiMsgs.ERROR_GENERIC,
288 "An error occurred during entity synchronization. Error: " + exc.getMessage());
292 return OperationState.OK;
298 private void performSync() {
299 while (selflinks.peek() != null) {
301 SelfLinkDescriptor linkDescriptor = selflinks.poll();
302 aaiWorkOnHand.decrementAndGet();
304 CrossEntityReferenceDescriptor descriptor = null;
306 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
308 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors()
309 .get(linkDescriptor.getEntityType());
311 if (descriptor == null) {
312 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
313 // go to next element in iterator
317 if (descriptor.hasCrossEntityReferences()) {
319 NetworkTransaction txn = new NetworkTransaction();
320 txn.setDescriptor(descriptor);
321 txn.setLink(linkDescriptor.getSelfLink());
322 txn.setQueryParameters(linkDescriptor.getDepthModifier());
323 txn.setOperationType(HttpMethod.GET);
324 txn.setEntityType(linkDescriptor.getEntityType());
326 aaiWorkOnHand.incrementAndGet();
328 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
329 .whenComplete((result, error) -> {
331 aaiWorkOnHand.decrementAndGet();
334 LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
336 if (result == null) {
337 LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
339 updateActiveInventoryCounters(result);
340 fetchDocumentForUpsert(result);
350 * Process entity type self links.
352 * @param operationResult the operation result
354 private void processEntityTypeSelfLinks(OperationResult operationResult) {
356 JsonNode rootNode = null;
358 final String jsonResult = operationResult.getResult();
360 if (jsonResult != null && jsonResult.length() > 0) {
363 rootNode = mapper.readTree(jsonResult);
364 } catch (IOException exc) {
365 // TODO // TODO -> LOG, waht should be logged here?
368 JsonNode resultData = rootNode.get("result-data");
369 ArrayNode resultDataArrayNode = null;
371 if (resultData.isArray()) {
372 resultDataArrayNode = (ArrayNode) resultData;
374 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
375 JsonNode element = null;
377 while (elementIterator.hasNext()) {
378 element = elementIterator.next();
380 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
381 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
383 CrossEntityReferenceDescriptor descriptor = null;
385 if (resourceType != null && resourceLink != null) {
386 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);
388 if (descriptor == null) {
389 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
390 // go to next element in iterator
393 if (descriptor.hasCrossEntityReferences()) {
394 selflinks.add(new SelfLinkDescriptor(
395 resourceLink,SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
406 * By providing the entity type and a json node for the entity, determine the
407 * primary key name(s) + primary key value(s) sufficient to build an entity query string
408 * of the following format:
410 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
412 * @return - a composite string in the above format or null
414 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
416 OxmEntityDescriptor entityDescriptor =
417 oxmEntityLookup.getEntityDescriptors().get(entityType);
419 String queryString = null;
421 if ( entityDescriptor != null ) {
423 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
424 final List<String> keyValues = new ArrayList<String>();
425 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
427 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
437 * Fetch document for upsert.
441 private void fetchDocumentForUpsert(NetworkTransaction txn) {
443 if (!txn.getOperationResult().wasSuccessful()) {
444 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
448 CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
449 .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
451 if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
453 final String jsonResult = txn.getOperationResult().getResult();
455 if (jsonResult != null && jsonResult.length() > 0) {
458 * Here's what we are going to do:
460 * <li>Extract primary key name and value from the parent type.
461 * <li>Extract the primary key and value from the nested child instance.
462 * <li>Build a generic query to discover the self-link for the nested-child-instance using
464 * <li>Set the self-link on the child.
465 * <li>Generate the id that will allow the elastic-search upsert to work.
466 * <li>Rinse and repeat.
469 CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
471 if (cerDefinition != null) {
472 JsonNode convertedNode = null;
474 convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
476 final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
478 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
480 NodeUtils.extractFieldValuesFromObject(convertedNode,
481 cerDefinition.getReferenceAttributes(),
482 extractedParentEntityAttributeValues);
484 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
485 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
486 nestedTargetEntityInstances);
488 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
490 if (cerDescriptor != null) {
492 String childEntityType = cerDefinition.getTargetEntityType();
493 OxmEntityDescriptor childDesciptor = oxmEntityLookup.getEntityDescriptors().get(childEntityType);
495 List<String> childPrimaryKeyNames = null;
497 if (childDesciptor != null) {
498 childPrimaryKeyNames = childDesciptor.getPrimaryKeyAttributeNames();
500 childPrimaryKeyNames = new ArrayList<String>();
503 List<String> childKeyValues = new ArrayList<String>();
504 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
506 String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
509 * Build generic-query to query child instance self-link from AAI
511 List<String> orderedQueryKeyParams = new ArrayList<String>();
514 * At present, there is an issue with resolving the self-link using the
515 * generic-query with nothing more than the service-instance identifier and the
516 * service-subscription. There is another level of detail we don't have access to
517 * unless we parse it out of the service-subscription self-link, which is a
518 * coupling I would like to avoid. Fortunately, there is a workaround, but only
519 * for service-instances, which is presently our only use-case for the
520 * cross-entity-reference in R1707. Going forwards hopefully there will be other
521 * ways to resolve a child self-link using parental embedded meta data that we
522 * don't currently have.
524 * The work-around with the service-instance entity-type is that it's possible to
525 * request the self-link using only the service-instance-id because of a
526 * historical AAI functional query requirement that it be possible to query a
527 * service-instance only by it's service-instance-id. This entity type is the only
528 * one in the system that can be queried this way which makes it a very limited
529 * workaround, but good enough for the current release.
532 if (SERVICE_INSTANCE.equals(childEntityType)) {
533 orderedQueryKeyParams.clear();
534 orderedQueryKeyParams.add(childEntityQueryKeyString);
536 orderedQueryKeyParams.add(parentEntityQueryString);
537 orderedQueryKeyParams.add(childEntityQueryKeyString);
540 String genericQueryStr = null;
542 genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
544 if (genericQueryStr != null) {
545 aaiWorkOnHand.incrementAndGet();
547 OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
548 genericQueryStr, "application/json",
549 aaiAdapter.getEndpointConfig().getNumRequestRetries());
551 aaiWorkOnHand.decrementAndGet();
553 if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
555 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
556 JsonNode genericQueryResult = null;
558 genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
560 if ( genericQueryResult != null ) {
562 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
564 String selfLink = null;
566 if (entityLinks.size() != 1) {
568 * an ambiguity exists where we can't reliably determine the self
569 * link, this should be a permanent error
571 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
573 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
576 IndexableCrossEntityReference icer =
577 getPopulatedDocument(targetEntityInstance, cerDescriptor);
579 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
580 icer.addCrossEntityReferenceValue(
581 parentCrossEntityReferenceAttributeValue);
584 icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));
590 link = elasticSearchAdapter
591 .buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
592 } catch (Exception exc) {
593 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
594 exc.getLocalizedMessage());
598 NetworkTransaction n2 = new NetworkTransaction();
600 n2.setEntityType(txn.getEntityType());
601 n2.setDescriptor(txn.getDescriptor());
602 n2.setOperationType(HttpMethod.GET);
604 esWorkOnHand.incrementAndGet();
607 new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
608 esExecutor).whenComplete((result, error) -> {
610 esWorkOnHand.decrementAndGet();
613 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
614 error.getLocalizedMessage());
616 updateElasticSearchCounters(result);
617 performDocumentUpsert(result, icer);
624 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
627 } catch (Exception exc) {
628 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
632 String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult();
633 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
637 String message = "Entity Sync failed because generic query str could not be determined.";
638 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
640 } catch (Exception exc) {
641 String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
642 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
648 } catch (IOException ioe) {
649 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
656 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
661 * Perform document upsert.
663 * @param esGetResult the es get result
664 * @param icer the icer
666 protected void performDocumentUpsert(NetworkTransaction esGetResult,
667 IndexableCrossEntityReference icer) {
671 * As part of the response processing we need to do the following:
672 * <li>1. Extract the version (if present), it will be the ETAG when we use the
673 * Search-Abstraction-Service
674 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
676 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
677 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
683 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
684 } catch (Exception exc) {
685 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
689 boolean wasEntryDiscovered = false;
690 String versionNumber = null;
691 if (esGetResult.getOperationResult().getResultCode() == 404) {
692 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
693 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
694 wasEntryDiscovered = true;
696 versionNumber = NodeUtils.extractFieldValueFromObject(
697 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
699 } catch (IOException exc) {
700 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
701 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
706 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
709 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
710 String.valueOf(esGetResult.getOperationResult().getResultCode()));
715 String jsonPayload = null;
716 if (wasEntryDiscovered) {
718 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
719 NodeUtils.extractObjectsByKey(
720 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
721 "_source", sourceObject);
723 if (!sourceObject.isEmpty()) {
724 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
725 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
726 ObjectReader updater = mapper.readerForUpdating(me);
727 MergableEntity merged = updater.readValue(icer.getAsJson());
728 jsonPayload = mapper.writeValueAsString(merged);
730 } catch (IOException exc) {
731 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
732 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
736 jsonPayload = icer.getAsJson();
739 if (wasEntryDiscovered) {
740 if (versionNumber != null && jsonPayload != null) {
742 String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
743 "default", icer.getId(), versionNumber, jsonPayload);
745 NetworkTransaction transactionTracker = new NetworkTransaction();
746 transactionTracker.setEntityType(esGetResult.getEntityType());
747 transactionTracker.setDescriptor(esGetResult.getDescriptor());
748 transactionTracker.setOperationType(HttpMethod.PUT);
750 esWorkOnHand.incrementAndGet();
751 supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
752 requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
753 .whenComplete((result, error) -> {
755 esWorkOnHand.decrementAndGet();
758 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
760 updateElasticSearchCounters(result);
761 processStoreDocumentResult(result, esGetResult, icer);
767 if (link != null && jsonPayload != null) {
769 NetworkTransaction updateElasticTxn = new NetworkTransaction();
770 updateElasticTxn.setLink(link);
771 updateElasticTxn.setEntityType(esGetResult.getEntityType());
772 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
773 updateElasticTxn.setOperationType(HttpMethod.PUT);
775 esWorkOnHand.incrementAndGet();
776 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
777 esPutExecutor).whenComplete((result, error) -> {
779 esWorkOnHand.decrementAndGet();
782 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
784 updateElasticSearchCounters(result);
785 processStoreDocumentResult(result, esGetResult, icer);
790 } catch (Exception exc) {
791 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
796 * Process store document result.
798 * @param esPutResult the es put result
799 * @param esGetResult the es get result
800 * @param icer the icer
802 private void processStoreDocumentResult(NetworkTransaction esPutResult,
803 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
805 OperationResult or = esPutResult.getOperationResult();
807 if (!or.wasSuccessful()) {
808 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
810 if (shouldAllowRetry(icer.getId())) {
812 esWorkOnHand.incrementAndGet();
814 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
815 retryQueue.push(rsc);
817 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
820 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
827 * Perform retry sync.
829 private void performRetrySync() {
830 while (retryQueue.peek() != null) {
832 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
835 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
836 NetworkTransaction txn = rsc.getNetworkTransaction();
840 // In this retry flow the icer object has already
841 // derived its fields
842 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
843 } catch (Exception exc) {
844 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
848 NetworkTransaction retryTransaction = new NetworkTransaction();
849 retryTransaction.setLink(link);
850 retryTransaction.setEntityType(txn.getEntityType());
851 retryTransaction.setDescriptor(txn.getDescriptor());
852 retryTransaction.setOperationType(HttpMethod.GET);
855 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
856 * that for this request already when queuing the failed PUT!
859 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
860 esExecutor).whenComplete((result, error) -> {
862 esWorkOnHand.decrementAndGet();
865 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
867 updateElasticSearchCounters(result);
868 performDocumentUpsert(result, icer);
878 * Should allow retry.
881 * @return true, if successful
883 private boolean shouldAllowRetry(String id) {
884 boolean isRetryAllowed = true;
885 if (retryLimitTracker.get(id) != null) {
886 Integer currentCount = retryLimitTracker.get(id);
887 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
888 isRetryAllowed = false;
889 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
891 Integer newCount = new Integer(currentCount.intValue() + 1);
892 retryLimitTracker.put(id, newCount);
896 Integer firstRetryCount = new Integer(1);
897 retryLimitTracker.put(id, firstRetryCount);
900 return isRetryAllowed;
904 * Gets the populated document.
906 * @param entityNode the entity node
907 * @param resultDescriptor the result descriptor
908 * @return the populated document
909 * @throws JsonProcessingException the json processing exception
910 * @throws IOException Signals that an I/O exception has occurred.
912 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
913 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
915 IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
917 icer.setEntityType(resultDescriptor.getEntityName());
919 List<String> primaryKeyValues = new ArrayList<String>();
920 String pkeyValue = null;
922 for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
923 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
924 if (pkeyValue != null) {
925 primaryKeyValues.add(pkeyValue);
927 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
931 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
932 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);