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 // 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.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 if (resultData.isArray()) {
367 resultDataArrayNode = (ArrayNode) resultData;
369 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
370 JsonNode element = null;
372 while (elementIterator.hasNext()) {
373 element = elementIterator.next();
375 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
376 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
378 CrossEntityReferenceDescriptor descriptor = null;
380 if (resourceType != null && resourceLink != null) {
381 descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);
383 if (descriptor == null) {
384 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
385 // go to next element in iterator
388 if (descriptor.hasCrossEntityReferences()) {
389 selflinks.add(new SelfLinkDescriptor(
390 resourceLink,SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
401 * By providing the entity type and a json node for the entity, determine the
402 * primary key name(s) + primary key value(s) sufficient to build an entity query string
403 * of the following format:
405 * <entityType>.<primaryKeyNames>:<primaryKeyValues>
407 * @return - a composite string in the above format or null
409 private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
411 OxmEntityDescriptor entityDescriptor =
412 oxmEntityLookup.getEntityDescriptors().get(entityType);
414 String queryString = null;
416 if ( entityDescriptor != null ) {
418 final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
419 final List<String> keyValues = new ArrayList<String>();
420 NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
422 queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
432 * Fetch document for upsert.
436 private void fetchDocumentForUpsert(NetworkTransaction txn) {
438 if (!txn.getOperationResult().wasSuccessful()) {
439 LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
443 CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
444 .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
446 if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
448 final String jsonResult = txn.getOperationResult().getResult();
450 if (jsonResult != null && jsonResult.length() > 0) {
453 * Here's what we are going to do:
455 * <li>Extract primary key name and value from the parent type.
456 * <li>Extract the primary key and value from the nested child instance.
457 * <li>Build a generic query to discover the self-link for the nested-child-instance using
459 * <li>Set the self-link on the child.
460 * <li>Generate the id that will allow the elastic-search upsert to work.
461 * <li>Rinse and repeat.
464 CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
466 if (cerDefinition != null) {
467 JsonNode convertedNode = null;
469 convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
471 final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
473 List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
475 NodeUtils.extractFieldValuesFromObject(convertedNode,
476 cerDefinition.getReferenceAttributes(),
477 extractedParentEntityAttributeValues);
479 List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
480 NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
481 nestedTargetEntityInstances);
483 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
485 if (cerDescriptor != null) {
487 String childEntityType = cerDefinition.getTargetEntityType();
489 List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeNames();
491 List<String> childKeyValues = new ArrayList<String>();
492 NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
494 String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
497 * Build generic-query to query child instance self-link from AAI
499 List<String> orderedQueryKeyParams = new ArrayList<String>();
502 * At present, there is an issue with resolving the self-link using the
503 * generic-query with nothing more than the service-instance identifier and the
504 * service-subscription. There is another level of detail we don't have access to
505 * unless we parse it out of the service-subscription self-link, which is a
506 * coupling I would like to avoid. Fortunately, there is a workaround, but only
507 * for service-instances, which is presently our only use-case for the
508 * cross-entity-reference in R1707. Going forwards hopefully there will be other
509 * ways to resolve a child self-link using parental embedded meta data that we
510 * don't currently have.
512 * The work-around with the service-instance entity-type is that it's possible to
513 * request the self-link using only the service-instance-id because of a
514 * historical AAI functional query requirement that it be possible to query a
515 * service-instance only by it's service-instance-id. This entity type is the only
516 * one in the system that can be queried this way which makes it a very limited
517 * workaround, but good enough for the current release.
520 if (SERVICE_INSTANCE.equals(childEntityType)) {
521 orderedQueryKeyParams.clear();
522 orderedQueryKeyParams.add(childEntityQueryKeyString);
524 orderedQueryKeyParams.add(parentEntityQueryString);
525 orderedQueryKeyParams.add(childEntityQueryKeyString);
528 String genericQueryStr = null;
530 genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
532 if (genericQueryStr != null) {
533 aaiWorkOnHand.incrementAndGet();
535 OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
536 genericQueryStr, "application/json",
537 aaiAdapter.getEndpointConfig().getNumRequestRetries());
539 aaiWorkOnHand.decrementAndGet();
541 if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
543 Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
544 JsonNode genericQueryResult = null;
546 genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
548 if ( genericQueryResult != null ) {
550 NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
552 String selfLink = null;
554 if (entityLinks.size() != 1) {
556 * an ambiguity exists where we can't reliably determine the self
557 * link, this should be a permanent error
559 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
561 selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
563 SearchableOxmEntityDescriptor searchableDescriptor = searchableEntityLookup.getSearchableEntityDescriptors().get( txn.getEntityType());
565 if (searchableDescriptor != null && searchableDescriptor.getSearchableAttributes().size() > 0) {
567 IndexableCrossEntityReference icer =
568 getPopulatedDocument(targetEntityInstance, cerDescriptor);
570 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
571 icer.addCrossEntityReferenceValue(
572 parentCrossEntityReferenceAttributeValue);
575 icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));
581 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
582 } catch (Exception exc) {
583 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
587 NetworkTransaction n2 = new NetworkTransaction();
589 n2.setEntityType(txn.getEntityType());
590 n2.setDescriptor(txn.getDescriptor());
591 n2.setOperationType(HttpMethod.GET);
593 esWorkOnHand.incrementAndGet();
595 supplyAsync(new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
596 esExecutor).whenComplete((result, error) -> {
598 esWorkOnHand.decrementAndGet();
601 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
603 updateElasticSearchCounters(result);
604 performDocumentUpsert(result, icer);
611 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
614 } catch (Exception exc) {
615 LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
619 String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult();
620 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
624 String message = "Entity Sync failed because generic query str could not be determined.";
625 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
627 } catch (Exception exc) {
628 String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
629 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
635 } catch (IOException ioe) {
636 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
643 LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
648 * Perform document upsert.
650 * @param esGetResult the es get result
651 * @param icer the icer
653 protected void performDocumentUpsert(NetworkTransaction esGetResult,
654 IndexableCrossEntityReference icer) {
658 * As part of the response processing we need to do the following:
659 * <li>1. Extract the version (if present), it will be the ETAG when we use the
660 * Search-Abstraction-Service
661 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
663 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
664 * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
670 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
671 } catch (Exception exc) {
672 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
676 boolean wasEntryDiscovered = false;
677 String versionNumber = null;
678 if (esGetResult.getOperationResult().getResultCode() == 404) {
679 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
680 } else if (esGetResult.getOperationResult().getResultCode() == 200) {
681 wasEntryDiscovered = true;
683 versionNumber = NodeUtils.extractFieldValueFromObject(
684 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
686 } catch (IOException exc) {
687 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
688 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
693 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
696 LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
697 String.valueOf(esGetResult.getOperationResult().getResultCode()));
702 String jsonPayload = null;
703 if (wasEntryDiscovered) {
705 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
706 NodeUtils.extractObjectsByKey(
707 NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
708 "_source", sourceObject);
710 if (!sourceObject.isEmpty()) {
711 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
712 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
713 ObjectReader updater = mapper.readerForUpdating(me);
714 MergableEntity merged = updater.readValue(icer.getAsJson());
715 jsonPayload = mapper.writeValueAsString(merged);
717 } catch (IOException exc) {
718 LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
719 icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
723 jsonPayload = icer.getAsJson();
726 if (wasEntryDiscovered) {
727 if (versionNumber != null && jsonPayload != null) {
729 String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
730 "default", icer.getId(), versionNumber, jsonPayload);
732 NetworkTransaction transactionTracker = new NetworkTransaction();
733 transactionTracker.setEntityType(esGetResult.getEntityType());
734 transactionTracker.setDescriptor(esGetResult.getDescriptor());
735 transactionTracker.setOperationType(HttpMethod.PUT);
737 esWorkOnHand.incrementAndGet();
738 supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
739 requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
740 .whenComplete((result, error) -> {
742 esWorkOnHand.decrementAndGet();
745 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
747 updateElasticSearchCounters(result);
748 processStoreDocumentResult(result, esGetResult, icer);
754 if (link != null && jsonPayload != null) {
756 NetworkTransaction updateElasticTxn = new NetworkTransaction();
757 updateElasticTxn.setLink(link);
758 updateElasticTxn.setEntityType(esGetResult.getEntityType());
759 updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
760 updateElasticTxn.setOperationType(HttpMethod.PUT);
762 esWorkOnHand.incrementAndGet();
763 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
764 esPutExecutor).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);
777 } catch (Exception exc) {
778 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
783 * Process store document result.
785 * @param esPutResult the es put result
786 * @param esGetResult the es get result
787 * @param icer the icer
789 private void processStoreDocumentResult(NetworkTransaction esPutResult,
790 NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
792 OperationResult or = esPutResult.getOperationResult();
794 if (!or.wasSuccessful()) {
795 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
797 if (shouldAllowRetry(icer.getId())) {
799 esWorkOnHand.incrementAndGet();
801 RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
802 retryQueue.push(rsc);
804 LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
807 LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
814 * Perform retry sync.
816 private void performRetrySync() {
817 while (retryQueue.peek() != null) {
819 RetryCrossEntitySyncContainer rsc = retryQueue.poll();
822 IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
823 NetworkTransaction txn = rsc.getNetworkTransaction();
827 // In this retry flow the icer object has already
828 // derived its fields
829 link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
830 } catch (Exception exc) {
831 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
835 NetworkTransaction retryTransaction = new NetworkTransaction();
836 retryTransaction.setLink(link);
837 retryTransaction.setEntityType(txn.getEntityType());
838 retryTransaction.setDescriptor(txn.getDescriptor());
839 retryTransaction.setOperationType(HttpMethod.GET);
842 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
843 * that for this request already when queuing the failed PUT!
846 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
847 esExecutor).whenComplete((result, error) -> {
849 esWorkOnHand.decrementAndGet();
852 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
854 updateElasticSearchCounters(result);
855 performDocumentUpsert(result, icer);
865 * Should allow retry.
868 * @return true, if successful
870 private boolean shouldAllowRetry(String id) {
871 boolean isRetryAllowed = true;
872 if (retryLimitTracker.get(id) != null) {
873 Integer currentCount = retryLimitTracker.get(id);
874 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
875 isRetryAllowed = false;
876 LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
878 Integer newCount = new Integer(currentCount.intValue() + 1);
879 retryLimitTracker.put(id, newCount);
883 Integer firstRetryCount = new Integer(1);
884 retryLimitTracker.put(id, firstRetryCount);
887 return isRetryAllowed;
891 * Gets the populated document.
893 * @param entityNode the entity node
894 * @param resultDescriptor the result descriptor
895 * @return the populated document
896 * @throws JsonProcessingException the json processing exception
897 * @throws IOException Signals that an I/O exception has occurred.
899 protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
900 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
902 IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
904 icer.setEntityType(resultDescriptor.getEntityName());
906 List<String> primaryKeyValues = new ArrayList<String>();
907 String pkeyValue = null;
909 for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
910 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
911 if (pkeyValue != null) {
912 primaryKeyValues.add(pkeyValue);
914 LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
918 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
919 icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);