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