Adding UI extensibility
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / viewinspect / sync / ViewInspectEntitySynchronizer.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.viewinspect.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.OxmEntityDescriptor;
44 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
45 import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
46 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
47 import org.onap.aai.sparky.dal.NetworkTransaction;
48 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig;
49 import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
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.MergableEntity;
58 import org.onap.aai.sparky.sync.entity.SearchableEntity;
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 SearchableEntitySynchronizer.
76  */
77 public class ViewInspectEntitySynchronizer extends AbstractEntitySynchronizer
78     implements IndexSynchronizer {
79
80   /**
81    * The Class RetrySearchableEntitySyncContainer.
82    */
83   private class RetrySearchableEntitySyncContainer {
84     NetworkTransaction txn;
85     SearchableEntity se;
86
87     /**
88      * Instantiates a new retry searchable entity sync container.
89      *
90      * @param txn the txn
91      * @param se the se
92      */
93     public RetrySearchableEntitySyncContainer(NetworkTransaction txn, SearchableEntity se) {
94       this.txn = txn;
95       this.se = se;
96     }
97
98     public NetworkTransaction getNetworkTransaction() {
99       return txn;
100     }
101
102     public SearchableEntity getSearchableEntity() {
103       return se;
104     }
105   }
106
107   private static final Logger LOG =
108       LoggerFactory.getInstance().getLogger(ViewInspectEntitySynchronizer.class);
109
110   private boolean allWorkEnumerated;
111   private Deque<SelfLinkDescriptor> selflinks;
112   private Deque<RetrySearchableEntitySyncContainer> retryQueue;
113   private Map<String, Integer> retryLimitTracker;
114   protected ExecutorService esPutExecutor;
115
116   /**
117    * Instantiates a new searchable entity synchronizer.
118    *
119    * @param indexName the index name
120    * @throws Exception the exception
121    */
122   public ViewInspectEntitySynchronizer(ElasticSearchSchemaConfig schemaConfig,
123       int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
124       NetworkStatisticsConfig esStatConfig) throws Exception {
125     super(LOG, "SES", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
126         aaiStatConfig, esStatConfig);
127     this.allWorkEnumerated = false;
128     this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
129     this.retryQueue = new ConcurrentLinkedDeque<RetrySearchableEntitySyncContainer>();
130     this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
131     this.synchronizerName = "Searchable Entity Synchronizer";
132     this.esPutExecutor = NodeUtils.createNamedExecutor("SES-ES-PUT", 5, LOG);
133     this.aaiEntityStats.intializeEntityCounters(
134         SearchableEntityLookup.getInstance().getSearchableEntityDescriptors().keySet());
135     this.esEntityStats.intializeEntityCounters(
136         SearchableEntityLookup.getInstance().getSearchableEntityDescriptors().keySet());
137     this.syncDurationInMs = -1;
138   }
139
140   /**
141    * Collect all the work.
142    *
143    * @return the operation state
144    */
145   private OperationState collectAllTheWork() {
146     final Map<String, String> contextMap = MDC.getCopyOfContextMap();
147     Map<String, SearchableOxmEntityDescriptor> descriptorMap =
148         SearchableEntityLookup.getInstance().getSearchableEntityDescriptors();
149
150     if (descriptorMap.isEmpty()) {
151       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES);
152       LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES);
153       return OperationState.ERROR;
154     }
155
156     Collection<String> syncTypes = descriptorMap.keySet();
157
158     /*
159      * Collection<String> syncTypes = new ArrayList<String>(); syncTypes.add("service-instance");
160      */
161
162     try {
163
164       /*
165        * launch a parallel async thread to process the documents for each entity-type (to max the of
166        * the configured executor anyway)
167        */
168
169       aaiWorkOnHand.set(syncTypes.size());
170
171       for (String key : syncTypes) {
172
173         supplyAsync(new Supplier<Void>() {
174
175           @Override
176           public Void get() {
177             MDC.setContextMap(contextMap);
178             OperationResult typeLinksResult = null;
179             try {
180               typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
181               aaiWorkOnHand.decrementAndGet();
182               processEntityTypeSelfLinks(typeLinksResult);
183             } catch (Exception exc) {
184               // TODO -> LOG, what should be logged here?
185             }
186
187             return null;
188           }
189
190         }, aaiExecutor).whenComplete((result, error) -> {
191
192           if (error != null) {
193             LOG.error(AaiUiMsgs.ERROR_GENERIC,
194                 "An error occurred getting data from AAI. Error = " + error.getMessage());
195           }
196         });
197
198       }
199
200       while (aaiWorkOnHand.get() != 0) {
201
202         if (LOG.isDebugEnabled()) {
203           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
204         }
205
206         Thread.sleep(1000);
207       }
208
209       aaiWorkOnHand.set(selflinks.size());
210       allWorkEnumerated = true;
211       syncEntityTypes();
212
213       while (!isSyncDone()) {
214         performRetrySync();
215         Thread.sleep(1000);
216       }
217
218       /*
219        * Make sure we don't hang on to retries that failed which could cause issues during future
220        * syncs
221        */
222       retryLimitTracker.clear();
223
224     } catch (Exception exc) {
225       // TODO -> LOG, waht should be logged here?
226     }
227
228     return OperationState.OK;
229   }
230
231   /*
232    * (non-Javadoc)
233    * 
234    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
235    */
236   @Override
237   public OperationState doSync() {
238     this.syncDurationInMs = -1;
239     String txnID = NodeUtils.getRandomTxnId();
240     MdcContext.initialize(txnID, "SearchableEntitySynchronizer", "", "Sync", "");
241
242     resetCounters();
243     this.allWorkEnumerated = false;
244     syncStartedTimeStampInMs = System.currentTimeMillis();
245     collectAllTheWork();
246
247     return OperationState.OK;
248   }
249
250   /**
251    * Process entity type self links.
252    *
253    * @param operationResult the operation result
254    */
255   private void processEntityTypeSelfLinks(OperationResult operationResult) {
256
257     JsonNode rootNode = null;
258
259     final String jsonResult = operationResult.getResult();
260
261     if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
262
263       try {
264         rootNode = mapper.readTree(jsonResult);
265       } catch (IOException exc) {
266         String message = "Could not deserialize JSON (representing operation result) as node tree. "
267             + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
268         LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
269       }
270
271       JsonNode resultData = rootNode.get("result-data");
272       ArrayNode resultDataArrayNode = null;
273
274       if (resultData.isArray()) {
275         resultDataArrayNode = (ArrayNode) resultData;
276
277         Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
278         JsonNode element = null;
279
280         while (elementIterator.hasNext()) {
281           element = elementIterator.next();
282
283           final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
284           final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
285
286           SearchableOxmEntityDescriptor descriptor = null;
287
288           if (resourceType != null && resourceLink != null) {
289
290             descriptor = SearchableEntityLookup.getInstance().getSearchableEntityDescriptors()
291                 .get(resourceType);
292
293             if (descriptor == null) {
294               LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
295               // go to next element in iterator
296               continue;
297             }
298
299             if (descriptor.hasSearchableAttributes()) {
300               selflinks.add(new SelfLinkDescriptor(resourceLink,
301                   SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
302             }
303
304           }
305         }
306       }
307     }
308
309   }
310
311   /**
312    * Sync entity types.
313    */
314   private void syncEntityTypes() {
315
316     while (selflinks.peek() != null) {
317
318       SelfLinkDescriptor linkDescriptor = selflinks.poll();
319       aaiWorkOnHand.decrementAndGet();
320
321       OxmEntityDescriptor descriptor = null;
322
323       if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
324
325         descriptor = OxmEntityLookup.getInstance().getEntityDescriptors()
326             .get(linkDescriptor.getEntityType());
327
328         if (descriptor == null) {
329           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
330           // go to next element in iterator
331           continue;
332         }
333
334         NetworkTransaction txn = new NetworkTransaction();
335         txn.setDescriptor(descriptor);
336         txn.setLink(linkDescriptor.getSelfLink());
337         txn.setOperationType(HttpMethod.GET);
338         txn.setEntityType(linkDescriptor.getEntityType());
339
340         aaiWorkOnHand.incrementAndGet();
341
342         supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
343             .whenComplete((result, error) -> {
344
345               aaiWorkOnHand.decrementAndGet();
346
347               if (error != null) {
348                 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
349               } else {
350                 if (result == null) {
351                   LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
352                       linkDescriptor.getSelfLink());
353                 } else {
354                   updateActiveInventoryCounters(result);
355                   fetchDocumentForUpsert(result);
356                 }
357               }
358             });
359       }
360
361     }
362
363   }
364
365   /**
366    * Perform document upsert.
367    *
368    * @param esGetTxn the es get txn
369    * @param se the se
370    */
371   protected void performDocumentUpsert(NetworkTransaction esGetTxn, SearchableEntity se) {
372     /**
373      * <p>
374      * <ul>
375      * As part of the response processing we need to do the following:
376      * <li>1. Extract the version (if present), it will be the ETAG when we use the
377      * Search-Abstraction-Service
378      * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
379      * tag
380      * <li>a) if version is null or RC=404, then standard put, no _update with version tag
381      * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
382      * </ul>
383      * </p>
384      */
385     String link = null;
386     try {
387       link = getElasticFullUrl("/" + se.getId(), getIndexName());
388     } catch (Exception exc) {
389       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
390       return;
391     }
392
393     String versionNumber = null;
394     boolean wasEntryDiscovered = false;
395     if (esGetTxn.getOperationResult().getResultCode() == 404) {
396       LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, se.getEntityPrimaryKeyValue());
397     } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
398       wasEntryDiscovered = true;
399       try {
400         versionNumber = NodeUtils.extractFieldValueFromObject(
401             NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
402             "_version");
403       } catch (IOException exc) {
404         String message =
405             "Error extracting version number from response, aborting searchable entity sync of "
406                 + se.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
407         LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
408         return;
409       }
410     } else {
411       /*
412        * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
413        * return.
414        */
415       LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
416           String.valueOf(esGetTxn.getOperationResult().getResultCode()));
417       return;
418     }
419
420     try {
421       String jsonPayload = null;
422       if (wasEntryDiscovered) {
423         try {
424           ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
425           NodeUtils.extractObjectsByKey(
426               NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
427               "_source", sourceObject);
428
429           if (!sourceObject.isEmpty()) {
430             String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
431             MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
432             ObjectReader updater = mapper.readerForUpdating(me);
433             MergableEntity merged = updater.readValue(NodeUtils.convertObjectToJson(se, false));
434             jsonPayload = mapper.writeValueAsString(merged);
435           }
436         } catch (IOException exc) {
437           String message =
438               "Error extracting source value from response, aborting searchable entity sync of "
439                   + se.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
440           LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
441           return;
442         }
443       } else {
444         jsonPayload = se.getAsJson();
445       }
446
447       if (wasEntryDiscovered) {
448         if (versionNumber != null && jsonPayload != null) {
449
450           String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(
451               getIndexName(), ElasticSearchConfig.getConfig().getType(), se.getId(), versionNumber,
452               jsonPayload);
453
454           NetworkTransaction transactionTracker = new NetworkTransaction();
455           transactionTracker.setEntityType(esGetTxn.getEntityType());
456           transactionTracker.setDescriptor(esGetTxn.getDescriptor());
457           transactionTracker.setOperationType(HttpMethod.PUT);
458
459           esWorkOnHand.incrementAndGet();
460           supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
461               requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
462                   .whenComplete((result, error) -> {
463
464                     esWorkOnHand.decrementAndGet();
465
466                     if (error != null) {
467                       String message = "Searchable entity sync UPDATE PUT error - "
468                           + error.getLocalizedMessage();
469                       LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
470                     } else {
471                       updateElasticSearchCounters(result);
472                       processStoreDocumentResult(result, esGetTxn, se);
473                     }
474                   });
475         }
476
477       } else {
478
479         if (link != null && jsonPayload != null) {
480
481           NetworkTransaction updateElasticTxn = new NetworkTransaction();
482           updateElasticTxn.setLink(link);
483           updateElasticTxn.setEntityType(esGetTxn.getEntityType());
484           updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
485           updateElasticTxn.setOperationType(HttpMethod.PUT);
486
487           esWorkOnHand.incrementAndGet();
488           supplyAsync(
489               new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
490               esPutExecutor).whenComplete((result, error) -> {
491
492                 esWorkOnHand.decrementAndGet();
493
494                 if (error != null) {
495                   String message =
496                       "Searchable entity sync UPDATE PUT error - " + error.getLocalizedMessage();
497                   LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
498                 } else {
499                   updateElasticSearchCounters(result);
500                   processStoreDocumentResult(result, esGetTxn, se);
501                 }
502               });
503         }
504       }
505     } catch (Exception exc) {
506       String message = "Exception caught during searchable entity sync PUT operation. Message - "
507           + exc.getLocalizedMessage();
508       LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
509     }
510   }
511
512   /**
513    * Populate searchable entity document.
514    *
515    * @param doc the doc
516    * @param result the result
517    * @param resultDescriptor the result descriptor
518    * @throws JsonProcessingException the json processing exception
519    * @throws IOException Signals that an I/O exception has occurred.
520    */
521   protected void populateSearchableEntityDocument(SearchableEntity doc, String result,
522       OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
523
524     doc.setEntityType(resultDescriptor.getEntityName());
525
526     JsonNode entityNode = mapper.readTree(result);
527
528     List<String> primaryKeyValues = new ArrayList<String>();
529     String pkeyValue = null;
530
531     SearchableOxmEntityDescriptor searchableDescriptor = SearchableEntityLookup.getInstance()
532         .getSearchableEntityDescriptors().get(resultDescriptor.getEntityName());
533
534     for (String keyName : searchableDescriptor.getPrimaryKeyAttributeNames()) {
535       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
536       if (pkeyValue != null) {
537         primaryKeyValues.add(pkeyValue);
538       } else {
539         String message = "populateSearchableEntityDocument(), pKeyValue is null for entityType = "
540             + resultDescriptor.getEntityName();
541         LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
542       }
543     }
544
545     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
546     doc.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
547
548     final List<String> searchTagFields = searchableDescriptor.getSearchableAttributes();
549
550     /*
551      * Based on configuration, use the configured field names for this entity-Type to build a
552      * multi-value collection of search tags for elastic search entity search criteria.
553      */
554     for (String searchTagField : searchTagFields) {
555       String searchTagValue = NodeUtils.getNodeFieldAsText(entityNode, searchTagField);
556       if (searchTagValue != null && !searchTagValue.isEmpty()) {
557         doc.addSearchTagWithKey(searchTagValue, searchTagField);
558       }
559     }
560   }
561
562   /**
563    * Fetch document for upsert.
564    *
565    * @param txn the txn
566    */
567   private void fetchDocumentForUpsert(NetworkTransaction txn) {
568     if (!txn.getOperationResult().wasSuccessful()) {
569       String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
570       LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
571       return;
572     }
573
574     SearchableOxmEntityDescriptor searchableDescriptor = SearchableEntityLookup.getInstance()
575         .getSearchableEntityDescriptors().get(txn.getDescriptor().getEntityName());
576
577     try {
578       if (searchableDescriptor.hasSearchableAttributes()) {
579
580         final String jsonResult = txn.getOperationResult().getResult();
581         if (jsonResult != null && jsonResult.length() > 0) {
582
583           SearchableEntity se = new SearchableEntity();
584           se.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink()));
585           populateSearchableEntityDocument(se, jsonResult, txn.getDescriptor());
586           se.deriveFields();
587
588           String link = null;
589           try {
590             link = getElasticFullUrl("/" + se.getId(), getIndexName());
591           } catch (Exception exc) {
592             LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
593           }
594
595           if (link != null) {
596             NetworkTransaction n2 = new NetworkTransaction();
597             n2.setLink(link);
598             n2.setEntityType(txn.getEntityType());
599             n2.setDescriptor(txn.getDescriptor());
600             n2.setOperationType(HttpMethod.GET);
601
602             esWorkOnHand.incrementAndGet();
603
604             supplyAsync(new PerformElasticSearchRetrieval(n2, elasticSearchAdapter), esExecutor)
605                 .whenComplete((result, error) -> {
606
607                   esWorkOnHand.decrementAndGet();
608
609                   if (error != null) {
610                     LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
611                   } else {
612                     updateElasticSearchCounters(result);
613                     performDocumentUpsert(result, se);
614                   }
615                 });
616           }
617         }
618
619       }
620     } catch (JsonProcessingException exc) {
621       // TODO -> LOG, waht should be logged here?
622     } catch (IOException exc) {
623       // TODO -> LOG, waht should be logged here?
624     }
625   }
626
627   /**
628    * Process store document result.
629    *
630    * @param esPutResult the es put result
631    * @param esGetResult the es get result
632    * @param se the se
633    */
634   private void processStoreDocumentResult(NetworkTransaction esPutResult,
635       NetworkTransaction esGetResult, SearchableEntity se) {
636
637     OperationResult or = esPutResult.getOperationResult();
638
639     if (!or.wasSuccessful()) {
640       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
641
642         if (shouldAllowRetry(se.getId())) {
643           esWorkOnHand.incrementAndGet();
644
645           RetrySearchableEntitySyncContainer rsc =
646               new RetrySearchableEntitySyncContainer(esGetResult, se);
647           retryQueue.push(rsc);
648
649           String message = "Store document failed during searchable entity synchronization"
650               + " due to version conflict. Entity will be re-synced.";
651           LOG.warn(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
652         }
653       } else {
654         String message =
655             "Store document failed during searchable entity synchronization with result code "
656                 + or.getResultCode() + " and result message " + or.getResult();
657         LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
658       }
659     }
660   }
661
662   /**
663    * Perform retry sync.
664    */
665   private void performRetrySync() {
666     while (retryQueue.peek() != null) {
667
668       RetrySearchableEntitySyncContainer rsc = retryQueue.poll();
669       if (rsc != null) {
670
671         SearchableEntity se = rsc.getSearchableEntity();
672         NetworkTransaction txn = rsc.getNetworkTransaction();
673
674         String link = null;
675         try {
676           /*
677            * In this retry flow the se object has already derived its fields
678            */
679           link = getElasticFullUrl("/" + se.getId(), getIndexName());
680         } catch (Exception exc) {
681           LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
682         }
683
684         if (link != null) {
685           NetworkTransaction retryTransaction = new NetworkTransaction();
686           retryTransaction.setLink(link);
687           retryTransaction.setEntityType(txn.getEntityType());
688           retryTransaction.setDescriptor(txn.getDescriptor());
689           retryTransaction.setOperationType(HttpMethod.GET);
690
691           /*
692            * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
693            * called incrementAndGet when queuing the failed PUT!
694            */
695
696           supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
697               esExecutor).whenComplete((result, error) -> {
698
699                 esWorkOnHand.decrementAndGet();
700
701                 if (error != null) {
702                   LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
703                 } else {
704                   updateElasticSearchCounters(result);
705                   performDocumentUpsert(result, se);
706                 }
707               });
708         }
709
710       }
711     }
712   }
713
714   /**
715    * Should allow retry.
716    *
717    * @param id the id
718    * @return true, if successful
719    */
720   private boolean shouldAllowRetry(String id) {
721     boolean isRetryAllowed = true;
722     if (retryLimitTracker.get(id) != null) {
723       Integer currentCount = retryLimitTracker.get(id);
724       if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
725         isRetryAllowed = false;
726         String message = "Searchable entity re-sync limit reached for " + id
727             + ", re-sync will no longer be attempted for this entity";
728         LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
729       } else {
730         Integer newCount = new Integer(currentCount.intValue() + 1);
731         retryLimitTracker.put(id, newCount);
732       }
733     } else {
734       Integer firstRetryCount = new Integer(1);
735       retryLimitTracker.put(id, firstRetryCount);
736     }
737
738     return isRetryAllowed;
739   }
740
741   @Override
742   public SynchronizerState getState() {
743     if (!isSyncDone()) {
744       return SynchronizerState.PERFORMING_SYNCHRONIZATION;
745     }
746
747     return SynchronizerState.IDLE;
748
749   }
750
751   /*
752    * (non-Javadoc)
753    * 
754    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
755    */
756   @Override
757   public String getStatReport(boolean showFinalReport) {
758     syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
759     return this.getStatReport(syncDurationInMs, showFinalReport);
760   }
761
762   /*
763    * (non-Javadoc)
764    * 
765    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
766    */
767   @Override
768   public void shutdown() {
769     this.shutdownExecutors();
770   }
771
772   @Override
773   protected boolean isSyncDone() {
774     int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
775
776     if (totalWorkOnHand > 0 || !allWorkEnumerated) {
777       return false;
778     }
779
780     return true;
781   }
782
783 }