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