changed the header license to new license
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / crossentityreference / sync / CrossEntityReferenceSynchronizer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21 package org.onap.aai.sparky.crossentityreference.sync;
22
23 import static java.util.concurrent.CompletableFuture.supplyAsync;
24
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;
31 import java.util.Map;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentLinkedDeque;
34 import java.util.concurrent.ExecutorService;
35 import java.util.function.Supplier;
36
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;
67 import org.slf4j.MDC;
68
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;
73
74 /**
75  * The Class CrossEntityReferenceSynchronizer.
76  */
77 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
78     implements IndexSynchronizer {
79
80   /**
81    * The Class RetryCrossEntitySyncContainer.
82    */
83   private class RetryCrossEntitySyncContainer {
84     NetworkTransaction txn;
85     IndexableCrossEntityReference icer;
86
87     /**
88      * Instantiates a new retry cross entity sync container.
89      *
90      * @param txn the txn
91      * @param icer the icer
92      */
93     public RetryCrossEntitySyncContainer(NetworkTransaction txn,
94         IndexableCrossEntityReference icer) {
95       this.txn = txn;
96       this.icer = icer;
97     }
98
99     public NetworkTransaction getNetworkTransaction() {
100       return txn;
101     }
102
103     public IndexableCrossEntityReference getIndexableCrossEntityReference() {
104       return icer;
105     }
106   }
107
108   private static final Logger LOG =
109       LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
110
111   private static final String SERVICE_INSTANCE = "service-instance";
112
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;
121   
122
123   /**
124    * Instantiates a new cross entity reference synchronizer.
125    *
126    * @param indexName the index name
127    * @throws Exception the exception
128    */
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());
146
147     this.esEntityStats.intializeEntityCounters(
148         crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
149     this.syncDurationInMs = -1;
150   }
151
152   /* (non-Javadoc)
153    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
154    */
155   @Override
156   public OperationState doSync() {
157     this.syncDurationInMs = -1;
158         String txnID = NodeUtils.getRandomTxnId();
159     MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
160         
161     resetCounters();
162     syncStartedTimeStampInMs = System.currentTimeMillis();
163     launchSyncFlow();
164     return OperationState.OK;
165   }
166
167   @Override
168   public SynchronizerState getState() {
169     if (!isSyncDone()) {
170       return SynchronizerState.PERFORMING_SYNCHRONIZATION;
171     }
172
173     return SynchronizerState.IDLE;
174   }
175
176   /* (non-Javadoc)
177    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
178    */
179   @Override
180   public String getStatReport(boolean showFinalReport) {
181     syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
182     return getStatReport(syncDurationInMs, showFinalReport);
183   }
184
185   /* (non-Javadoc)
186    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
187    */
188   @Override
189   public void shutdown() {
190     this.shutdownExecutors();
191   }
192
193   @Override
194   protected boolean isSyncDone() {
195     int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
196
197     if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
198       return false;
199     }
200
201     return true;
202   }
203
204   /**
205    * Launch sync flow.
206    *
207    * @return the operation state
208    */
209   private OperationState launchSyncFlow() {
210         final Map<String,String> contextMap = MDC.getCopyOfContextMap();
211     Map<String, CrossEntityReferenceDescriptor> descriptorMap =
212         crossEntityReferenceLookup.getCrossReferenceEntityDescriptors();
213
214     if (descriptorMap.isEmpty()) {
215       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
216
217       return OperationState.ERROR;
218     }
219
220     Collection<String> syncTypes = descriptorMap.keySet();
221
222     try {
223
224       /*
225        * launch a parallel async thread to process the documents for each entity-type (to max the of
226        * the configured executor anyway)
227        */
228
229       aaiWorkOnHand.set(syncTypes.size());
230
231       for (String key : syncTypes) {
232
233         supplyAsync(new Supplier<Void>() {
234
235           @Override
236           public Void get() {
237                 MDC.setContextMap(contextMap);
238             OperationResult typeLinksResult = null;
239             try {
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());
246             }
247
248             return null;
249           }
250
251         }, aaiExecutor).whenComplete((result, error) -> {
252           if (error != null) {
253             LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
254           }
255         });
256       }
257
258       while (aaiWorkOnHand.get() != 0) {
259
260         if (LOG.isDebugEnabled()) {
261           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
262         }
263
264         Thread.sleep(1000);
265       }
266
267       aaiWorkOnHand.set(selflinks.size());
268       isAllWorkEnumerated = true;
269       performSync();
270
271       while (!isSyncDone()) {
272         performRetrySync();
273         Thread.sleep(1000);
274       }
275
276       /*
277        * Make sure we don't hang on to retries that failed which could cause issues during future
278        * syncs
279        */
280       retryLimitTracker.clear();
281
282     } catch (Exception exc) {
283       LOG.error(AaiUiMsgs.ERROR_GENERIC,
284           "An error occurred during entity synchronization. Error: " + exc.getMessage());
285
286     }
287
288     return OperationState.OK;
289   }
290
291   /**
292    * Perform sync.
293    */
294   private void performSync() {
295     while (selflinks.peek() != null) {
296
297       SelfLinkDescriptor linkDescriptor = selflinks.poll();
298       aaiWorkOnHand.decrementAndGet();
299
300       CrossEntityReferenceDescriptor descriptor = null;
301
302       if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
303
304         descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors()
305             .get(linkDescriptor.getEntityType());
306
307         if (descriptor == null) {
308           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
309           // go to next element in iterator
310           continue;
311         }
312
313         if (descriptor.hasCrossEntityReferences()) {
314
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());
321
322           aaiWorkOnHand.incrementAndGet();
323
324           supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
325               .whenComplete((result, error) -> {
326
327                 aaiWorkOnHand.decrementAndGet();
328
329                 if (error != null) {
330                   LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
331                 } else {
332                   if (result == null) {
333                     LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
334                   } else {
335                     updateActiveInventoryCounters(result);
336                     fetchDocumentForUpsert(result);
337                   }
338                 }
339               });
340         }
341       }
342     }
343   }
344
345   /**
346    * Process entity type self links.
347    *
348    * @param operationResult the operation result
349    */
350   private void processEntityTypeSelfLinks(OperationResult operationResult) {
351
352     JsonNode rootNode = null;
353
354     final String jsonResult = operationResult.getResult();
355
356     if (jsonResult != null && jsonResult.length() > 0) {
357
358       try {
359         rootNode = mapper.readTree(jsonResult);
360       } catch (IOException exc) {
361         // TODO // TODO -> LOG, waht should be logged here?
362       }
363
364       JsonNode resultData = rootNode.get("result-data");
365       ArrayNode resultDataArrayNode = null;
366
367       if (resultData.isArray()) {
368         resultDataArrayNode = (ArrayNode) resultData;
369
370         Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
371         JsonNode element = null;
372
373         while (elementIterator.hasNext()) {
374           element = elementIterator.next();
375
376           final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
377           final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
378
379           CrossEntityReferenceDescriptor descriptor = null;
380
381           if (resourceType != null && resourceLink != null) {
382             descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);
383
384             if (descriptor == null) {
385               LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
386               // go to next element in iterator
387               continue;
388             }
389             if (descriptor.hasCrossEntityReferences()) {
390               selflinks.add(new SelfLinkDescriptor(
391                   resourceLink,SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
392             }
393           }
394         }
395       }
396     }
397   }
398
399   
400   
401   /**
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:
405    * 
406    *      <entityType>.<primaryKeyNames>:<primaryKeyValues>
407    * 
408    * @return - a composite string in the above format or null
409    */
410   private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
411     
412     OxmEntityDescriptor entityDescriptor =
413         oxmEntityLookup.getEntityDescriptors().get(entityType);
414     
415     String queryString = null;
416     
417     if ( entityDescriptor != null ) {
418
419       final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
420       final List<String> keyValues = new ArrayList<String>();
421       NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
422
423       queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
424
425     } 
426     
427     return queryString;
428
429     
430   }
431   
432   /**
433    * Fetch document for upsert.
434    *
435    * @param txn the txn
436    */
437   private void fetchDocumentForUpsert(NetworkTransaction txn) {
438     
439     if (!txn.getOperationResult().wasSuccessful()) {
440       LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
441       return;
442     }
443
444     CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
445         .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
446     
447     if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
448
449       final String jsonResult = txn.getOperationResult().getResult();
450       
451       if (jsonResult != null && jsonResult.length() > 0) {
452         
453         /**
454          * Here's what we are going to do:
455          * 
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
459          * parent and child.
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.
463          */
464           
465           CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
466
467           if (cerDefinition != null) {
468             JsonNode convertedNode = null;
469             try {
470               convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
471               
472               final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
473               
474               List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
475
476               NodeUtils.extractFieldValuesFromObject(convertedNode,
477                   cerDefinition.getReferenceAttributes(),
478                   extractedParentEntityAttributeValues);
479
480               List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
481               NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
482                   nestedTargetEntityInstances);
483
484               for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
485
486                 if (cerDescriptor != null) {
487                   
488                   String childEntityType = cerDefinition.getTargetEntityType();
489                   OxmEntityDescriptor childDesciptor = oxmEntityLookup.getEntityDescriptors().get(childEntityType);
490                   
491                   List<String> childPrimaryKeyNames = null;
492                   
493                   if (childDesciptor != null) {
494                     childPrimaryKeyNames = childDesciptor.getPrimaryKeyAttributeNames();
495                   } else {
496                     childPrimaryKeyNames = new ArrayList<String>();
497                   }
498                                 
499                   List<String> childKeyValues = new ArrayList<String>();
500                   NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
501                   
502                   String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
503                   
504                   /**
505                    * Build generic-query to query child instance self-link from AAI
506                    */
507                   List<String> orderedQueryKeyParams = new ArrayList<String>();
508
509                   /**
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.
519                    * 
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.
526                    */
527
528                   if (SERVICE_INSTANCE.equals(childEntityType)) {
529                     orderedQueryKeyParams.clear();
530                     orderedQueryKeyParams.add(childEntityQueryKeyString);
531                   } else {
532                     orderedQueryKeyParams.add(parentEntityQueryString);
533                     orderedQueryKeyParams.add(childEntityQueryKeyString);
534                   }
535
536                   String genericQueryStr = null;
537                   try {
538                     genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
539                     
540                     if (genericQueryStr != null) {
541                       aaiWorkOnHand.incrementAndGet();
542
543                       OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
544                           genericQueryStr, "application/json",
545                           aaiAdapter.getEndpointConfig().getNumRequestRetries());
546
547                       aaiWorkOnHand.decrementAndGet();
548
549                       if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
550                         
551                         Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
552                         JsonNode genericQueryResult = null;
553                         try {
554                           genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
555                           
556                           if ( genericQueryResult != null ) {
557                             
558                             NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
559
560                             String selfLink = null;
561
562                             if (entityLinks.size() != 1) {
563                               /**
564                                * an ambiguity exists where we can't reliably determine the self
565                                * link, this should be a permanent error
566                                */
567                               LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
568                           } else {
569                             selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
570
571
572                             IndexableCrossEntityReference icer =
573                                 getPopulatedDocument(targetEntityInstance, cerDescriptor);
574
575                             for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
576                               icer.addCrossEntityReferenceValue(
577                                   parentCrossEntityReferenceAttributeValue);
578                             }
579
580                             icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));
581
582                             icer.deriveFields();
583
584                             String link = null;
585                             try {
586                               link = elasticSearchAdapter
587                                   .buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
588                             } catch (Exception exc) {
589                               LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
590                                   exc.getLocalizedMessage());
591                             }
592
593                             if (link != null) {
594                               NetworkTransaction n2 = new NetworkTransaction();
595                               n2.setLink(link);
596                               n2.setEntityType(txn.getEntityType());
597                               n2.setDescriptor(txn.getDescriptor());
598                               n2.setOperationType(HttpMethod.GET);
599
600                               esWorkOnHand.incrementAndGet();
601
602                               supplyAsync(
603                                   new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
604                                   esExecutor).whenComplete((result, error) -> {
605
606                                     esWorkOnHand.decrementAndGet();
607
608                                     if (error != null) {
609                                       LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
610                                           error.getLocalizedMessage());
611                                     } else {
612                                       updateElasticSearchCounters(result);
613                                       performDocumentUpsert(result, icer);
614                                     }
615                                   });
616                             }
617
618                           }
619                           } else {
620                             LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
621                           }
622
623                         } catch (Exception exc) {
624                           LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
625                         }
626                         
627                       } else {
628                         String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult(); 
629                         LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
630                       }
631                       
632                     } else {
633                       String message = "Entity Sync failed because generic query str could not be determined.";
634                       LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
635                     }
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);
639                   }
640                   
641                 }
642               }
643               
644             } catch (IOException ioe) {
645               LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
646             }
647           }
648           
649         } 
650       
651     } else {
652       LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
653     }
654   }
655
656   /**
657    * Perform document upsert.
658    *
659    * @param esGetResult the es get result
660    * @param icer the icer
661    */
662   protected void performDocumentUpsert(NetworkTransaction esGetResult,
663       IndexableCrossEntityReference icer) {
664     /**
665      * <p>
666      * <ul>
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
671      * tag
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
674      * </ul>
675      * </p>
676      */
677     String link = null;
678     try {
679       link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
680     } catch (Exception exc) {
681       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
682       return;
683     }
684
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;
691       try {
692         versionNumber = NodeUtils.extractFieldValueFromObject(
693             NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
694             "_version");
695       } catch (IOException exc) {
696         LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
697             icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
698         return;
699       }
700     } else {
701       /*
702        * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
703        * return.
704        */
705       LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
706           String.valueOf(esGetResult.getOperationResult().getResultCode()));
707       return;
708     }
709
710     try {
711       String jsonPayload = null;
712       if (wasEntryDiscovered) {
713         try {
714           ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
715           NodeUtils.extractObjectsByKey(
716               NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
717               "_source", sourceObject);
718
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);
725           }
726         } catch (IOException exc) {
727           LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
728               icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
729           return;
730         }
731       } else {
732         jsonPayload = icer.getAsJson();
733       }
734
735       if (wasEntryDiscovered) {
736         if (versionNumber != null && jsonPayload != null) {
737
738           String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
739               "default", icer.getId(), versionNumber, jsonPayload);
740
741           NetworkTransaction transactionTracker = new NetworkTransaction();
742           transactionTracker.setEntityType(esGetResult.getEntityType());
743           transactionTracker.setDescriptor(esGetResult.getDescriptor());
744           transactionTracker.setOperationType(HttpMethod.PUT);
745
746           esWorkOnHand.incrementAndGet();
747           supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
748               requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
749                   .whenComplete((result, error) -> {
750
751                     esWorkOnHand.decrementAndGet();
752
753                     if (error != null) {
754                       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
755                     } else {
756                       updateElasticSearchCounters(result);
757                       processStoreDocumentResult(result, esGetResult, icer);
758                     }
759                   });
760         }
761
762       } else {
763         if (link != null && jsonPayload != null) {
764
765           NetworkTransaction updateElasticTxn = new NetworkTransaction();
766           updateElasticTxn.setLink(link);
767           updateElasticTxn.setEntityType(esGetResult.getEntityType());
768           updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
769           updateElasticTxn.setOperationType(HttpMethod.PUT);
770
771           esWorkOnHand.incrementAndGet();
772           supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
773               esPutExecutor).whenComplete((result, error) -> {
774
775                 esWorkOnHand.decrementAndGet();
776
777                 if (error != null) {
778                   LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
779                 } else {
780                   updateElasticSearchCounters(result);
781                   processStoreDocumentResult(result, esGetResult, icer);
782                 }
783               });
784         }
785       }
786     } catch (Exception exc) {
787       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
788     }
789   }
790
791   /**
792    * Process store document result.
793    *
794    * @param esPutResult the es put result
795    * @param esGetResult the es get result
796    * @param icer the icer
797    */
798   private void processStoreDocumentResult(NetworkTransaction esPutResult,
799       NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
800
801     OperationResult or = esPutResult.getOperationResult();
802
803     if (!or.wasSuccessful()) {
804       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
805
806         if (shouldAllowRetry(icer.getId())) {
807
808           esWorkOnHand.incrementAndGet();
809
810           RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
811           retryQueue.push(rsc);
812
813           LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
814         }
815       } else {
816         LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
817             or.getResult());
818       }
819     }
820   }
821
822   /**
823    * Perform retry sync.
824    */
825   private void performRetrySync() {
826     while (retryQueue.peek() != null) {
827
828       RetryCrossEntitySyncContainer rsc = retryQueue.poll();
829       if (rsc != null) {
830
831         IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
832         NetworkTransaction txn = rsc.getNetworkTransaction();
833
834         String link = null;
835         try {
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());
841         }
842
843         if (link != null) {
844           NetworkTransaction retryTransaction = new NetworkTransaction();
845           retryTransaction.setLink(link);
846           retryTransaction.setEntityType(txn.getEntityType());
847           retryTransaction.setDescriptor(txn.getDescriptor());
848           retryTransaction.setOperationType(HttpMethod.GET);
849
850           /*
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!
853            */
854
855           supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
856               esExecutor).whenComplete((result, error) -> {
857
858                 esWorkOnHand.decrementAndGet();
859
860                 if (error != null) {
861                   LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
862                 } else {
863                   updateElasticSearchCounters(result);
864                   performDocumentUpsert(result, icer);
865                 }
866               });
867         }
868
869       }
870     }
871   }
872
873   /**
874    * Should allow retry.
875    *
876    * @param id the id
877    * @return true, if successful
878    */
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);
886       } else {
887         Integer newCount = new Integer(currentCount.intValue() + 1);
888         retryLimitTracker.put(id, newCount);
889       }
890
891     } else {
892       Integer firstRetryCount = new Integer(1);
893       retryLimitTracker.put(id, firstRetryCount);
894     }
895
896     return isRetryAllowed;
897   }
898
899   /**
900    * Gets the populated document.
901    *
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.
907    */
908   protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
909       OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
910
911     IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
912
913     icer.setEntityType(resultDescriptor.getEntityName());
914
915     List<String> primaryKeyValues = new ArrayList<String>();
916     String pkeyValue = null;
917
918     for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
919       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
920       if (pkeyValue != null) {
921         primaryKeyValues.add(pkeyValue);
922       } else {
923         LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
924       }
925     }
926
927     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
928     icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
929
930     return icer;
931
932   }
933 }