Merge "[AAI] Attempting to fix a compile run version mismatch in sparky"
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / autosuggestion / sync / AutosuggestionSynchronizer.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.autosuggestion.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.Arrays;
28 import java.util.Collection;
29 import java.util.Deque;
30 import java.util.EnumSet;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.concurrent.ConcurrentHashMap;
36 import java.util.concurrent.ConcurrentLinkedDeque;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.atomic.AtomicInteger;
39 import java.util.function.Consumer;
40 import java.util.function.Supplier;
41
42 import org.onap.aai.cl.api.Logger;
43 import org.onap.aai.cl.eelf.LoggerFactory;
44 import org.onap.aai.cl.mdc.MdcContext;
45 import org.onap.aai.restclient.client.OperationResult;
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.SuggestionEntityDescriptor;
49 import org.onap.aai.sparky.config.oxm.SuggestionEntityLookup;
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.search.filters.config.FiltersConfig;
55 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
56 import org.onap.aai.sparky.sync.IndexSynchronizer;
57 import org.onap.aai.sparky.sync.SynchronizerConstants;
58 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
59 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
60 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
61 import org.onap.aai.sparky.sync.entity.SuggestionSearchEntity;
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.PerformSearchServicePut;
66 import org.onap.aai.sparky.sync.task.PerformSearchServiceRetrieval;
67 import org.onap.aai.sparky.util.NodeUtils;
68 import org.onap.aai.sparky.util.SuggestionsPermutation;
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.node.ArrayNode;
74
75 /**
76  * The Class AutosuggestionSynchronizer.
77  */
78 public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer
79     implements IndexSynchronizer {
80
81   private class RetrySuggestionEntitySyncContainer {
82     NetworkTransaction txn;
83     SuggestionSearchEntity ssec;
84
85     /**
86      * Instantiates a new RetrySuggestionEntitySyncContainer.
87      *
88      * @param txn the txn
89      * @param icer the icer
90      */
91     public RetrySuggestionEntitySyncContainer(NetworkTransaction txn, SuggestionSearchEntity icer) {
92       this.txn = txn;
93       this.ssec = icer;
94     }
95
96     public NetworkTransaction getNetworkTransaction() {
97       return txn;
98     }
99
100     public SuggestionSearchEntity getSuggestionSearchEntity() {
101       return ssec;
102     }
103   }
104
105   private static final Logger LOG =
106       LoggerFactory.getInstance().getLogger(AutosuggestionSynchronizer.class);
107   private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
108
109   private boolean allWorkEnumerated;
110   private Deque<SelfLinkDescriptor> selflinks;
111   private ConcurrentHashMap<String, AtomicInteger> entityCounters;
112   private boolean syncInProgress;
113   private Map<String, String> contextMap;
114   protected ExecutorService esPutExecutor;
115   private Deque<RetrySuggestionEntitySyncContainer> retryQueue;
116   private Map<String, Integer> retryLimitTracker;
117   private OxmEntityLookup oxmEntityLookup;
118   private SuggestionEntityLookup suggestionEntityLookup;
119   private FiltersConfig filtersConfig;
120
121   /**
122    * Instantiates a new historical entity summarizer.
123    *
124    * @throws Exception the exception
125    */
126   public AutosuggestionSynchronizer(ElasticSearchSchemaConfig schemaConfig, int internalSyncWorkers,
127       int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
128       NetworkStatisticsConfig esStatConfig, OxmEntityLookup oxmEntityLookup,
129       SuggestionEntityLookup suggestionEntityLookup, FiltersConfig filtersConfig) throws Exception {
130
131     super(LOG, "ASES-" + schemaConfig.getIndexName().toUpperCase(), internalSyncWorkers, aaiWorkers,
132         esWorkers, schemaConfig.getIndexName(), aaiStatConfig, esStatConfig);
133     
134     this.oxmEntityLookup = oxmEntityLookup;
135     this.suggestionEntityLookup = suggestionEntityLookup;
136     this.allWorkEnumerated = false;
137     this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
138     this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
139     this.synchronizerName = "Autosuggestion Entity Synchronizer";
140     this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
141     this.syncInProgress = false;
142     this.contextMap = MDC.getCopyOfContextMap();
143     this.esPutExecutor = NodeUtils.createNamedExecutor("SUES-ES-PUT", 5, LOG);
144     this.retryQueue = new ConcurrentLinkedDeque<RetrySuggestionEntitySyncContainer>();
145     this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
146     this.syncDurationInMs = -1;
147     this.filtersConfig = filtersConfig;
148   }
149
150   /**
151    * Collect all the work.
152    *
153    * @return the operation state
154    */
155   private OperationState collectAllTheWork() {
156     final Map<String, String> contextMap = MDC.getCopyOfContextMap();
157     Map<String, SuggestionEntityDescriptor> descriptorMap =
158         suggestionEntityLookup.getSuggestionSearchEntityDescriptors();
159
160     if (descriptorMap.isEmpty()) {
161       this.allWorkEnumerated = true;
162       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
163       LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
164       return OperationState.ERROR;
165     }
166
167     Collection<String> syncTypes = descriptorMap.keySet();
168
169     try {
170
171       /*
172        * launch a parallel async thread to process the documents for each entity-type (to max the of
173        * the configured executor anyway)
174        */
175
176       aaiWorkOnHand.set(syncTypes.size());
177
178       for (String key : syncTypes) {
179
180         supplyAsync(new Supplier<Void>() {
181
182           @Override
183           public Void get() {
184             MDC.setContextMap(contextMap);
185             OperationResult typeLinksResult = null;
186             try {
187               typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
188               aaiWorkOnHand.decrementAndGet();
189               processEntityTypeSelfLinks(typeLinksResult);
190             } catch (Exception exc) {
191               LOG.error(AaiUiMsgs.ERROR_GENERIC,
192                   "An error occurred while processing entity self-links. Error: "
193                       + exc.getMessage());
194             }
195
196             return null;
197           }
198
199         }, aaiExecutor).whenComplete((result, error) -> {
200
201           if (error != null) {
202             LOG.error(AaiUiMsgs.ERROR_GENERIC,
203                 "An error occurred getting data from AAI. Error = " + error.getMessage());
204           }
205         });
206
207       }
208
209       while (aaiWorkOnHand.get() != 0) {
210
211         if (LOG.isDebugEnabled()) {
212           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
213         }
214
215         Thread.sleep(1000);
216       }
217
218       aaiWorkOnHand.set(selflinks.size());
219       allWorkEnumerated = true;
220       syncEntityTypes();
221
222       while (!isSyncDone()) {
223         performRetrySync();
224         Thread.sleep(1000);
225       }
226
227       /*
228        * Make sure we don't hang on to retries that failed which could cause issues during future
229        * syncs
230        */
231       retryLimitTracker.clear();
232     } catch (InterruptedException e) {
233       // Restore interrupted state...
234       Thread.currentThread().interrupt();
235     } catch (Exception exc) {
236       LOG.error(AaiUiMsgs.ERROR_GENERIC,
237           "An error occurred while performing the sync.  Error: " + exc.getMessage());
238     }
239
240     return OperationState.OK;
241
242   }
243
244   /*
245    * (non-Javadoc)
246    * 
247    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
248    */
249   @Override
250   public OperationState doSync() {
251     this.syncDurationInMs = -1;
252     syncStartedTimeStampInMs = System.currentTimeMillis();
253     String txnID = NodeUtils.getRandomTxnId();
254     MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", "");
255
256     return collectAllTheWork();
257   }
258
259   /**
260    * Process entity type self links.
261    *
262    * @param operationResult the operation result
263    */
264   private void processEntityTypeSelfLinks(OperationResult operationResult) {
265
266     if (operationResult == null) {
267       return;
268     }
269
270     final String jsonResult = operationResult.getResult();
271
272     if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
273
274       try {
275         JsonNode rootNode = mapper.readTree(jsonResult);
276         JsonNode resultData = rootNode.get("result-data");
277
278         if (resultData.isArray()) {
279           ArrayNode resultDataArrayNode = (ArrayNode) resultData;
280
281           Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
282
283           while (elementIterator.hasNext()) {
284             JsonNode element = elementIterator.next();
285
286             final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
287             final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
288
289             if (resourceType != null && resourceLink != null) {
290
291               OxmEntityDescriptor descriptor = oxmEntityLookup.getEntityDescriptors().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               selflinks.add(new SelfLinkDescriptor(resourceLink,
299                       SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
300             }
301           }
302         }
303       } catch (IOException exc) {
304         String message = "Could not deserialize JSON (representing operation result) as node tree. "
305                 + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
306         LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
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.getEntityDescriptors().get(linkDescriptor.getEntityType());
326
327         if (descriptor == null) {
328           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
329           // go to next element in iterator
330           continue;
331         }
332
333         NetworkTransaction txn = new NetworkTransaction();
334         txn.setDescriptor(descriptor);
335         txn.setLink(linkDescriptor.getSelfLink());
336         txn.setOperationType(HttpMethod.GET);
337         txn.setEntityType(linkDescriptor.getEntityType());
338
339         aaiWorkOnHand.incrementAndGet();
340
341         supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter,"sync"), aaiExecutor)
342             .whenComplete((result, error) -> {
343
344               aaiWorkOnHand.decrementAndGet();
345
346               if (error != null) {
347                 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
348               } else {
349                 if (result == null) {
350                   LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
351                       linkDescriptor.getSelfLink());
352                 } else {
353                   updateActiveInventoryCounters(result);
354                   fetchDocumentForUpsert(result);
355                 }
356               }
357             });
358       }
359
360     }
361
362   }
363
364   /*
365    * Return a set of valid suggestion attributes for the provided entityName that are present in the
366    * JSON
367    * 
368    * @param node JSON node in which the attributes should be found
369    * 
370    * @param entityName Name of the entity
371    * 
372    * @return List of all valid suggestion attributes(key's)
373    */
374   public List<String> getSuggestableAttrNamesFromReponse(JsonNode node, String entityName) {
375     List<String> suggestableAttr = new ArrayList<String>();
376
377     HashMap<String, String> desc =
378         suggestionEntityLookup.getSuggestionSearchEntityOxmModel().get(entityName);
379
380     if (desc != null) {
381
382       String attr = desc.get("suggestibleAttributes");
383
384       if (attr != null) {
385         suggestableAttr = Arrays.asList(attr.split(","));
386         List<String> suggestableValue = new ArrayList<>();
387         for (String attribute : suggestableAttr) {
388           if (node.get(attribute) != null && node.get(attribute).asText().length() > 0) {
389             suggestableValue.add(attribute);
390           }
391         }
392         return suggestableValue;
393       }
394     }
395
396     return new ArrayList<>();
397   }
398
399   /**
400    * Fetch all the documents for upsert. Based on the number of permutations that are available the
401    * number of documents will be different
402    *
403    * @param txn the txn
404    */
405   private void fetchDocumentForUpsert(NetworkTransaction txn) {
406     if (!txn.getOperationResult().wasSuccessful()) {
407       String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
408       LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
409       return;
410     }
411     try {
412       final String jsonResult = txn.getOperationResult().getResult();
413
414       if (jsonResult != null && jsonResult.length() > 0) {
415
416         // Step 1: Calculate the number of possible permutations of attributes
417         String entityName = txn.getDescriptor().getEntityName();
418         JsonNode entityNode = mapper.readTree(jsonResult);
419
420         List<String> availableSuggestableAttrName =
421             getSuggestableAttrNamesFromReponse(entityNode, entityName);
422         
423         ArrayList<ArrayList<String>> uniqueLists =
424             SuggestionsPermutation.getNonEmptyUniqueLists(availableSuggestableAttrName);
425         // Now we have a list of all possible permutations for the status that are
426         // defined for this entity type. Try inserting a document for every combination.
427         for (ArrayList<String> uniqueList : uniqueLists) {
428
429           SuggestionSearchEntity sse = new SuggestionSearchEntity(filtersConfig, suggestionEntityLookup);
430           sse.setSuggestableAttr(uniqueList);
431           sse.setFilterBasedPayloadFromResponse(entityNode, entityName, uniqueList);
432           sse.setLink(ActiveInventoryAdapter.extractResourcePath(txn.getLink()));
433           populateSuggestionSearchEntityDocument(sse, jsonResult, txn);
434           // The unique id for the document will be created at derive fields
435           sse.deriveFields();
436           // Insert the document only if it has valid statuses
437           if (sse.isSuggestableDoc()) {
438             String link = null;
439             try {
440               link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), sse.getId());
441             } catch (Exception exc) {
442               LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
443             }
444
445             if (link != null) {
446               NetworkTransaction n2 = new NetworkTransaction();
447               n2.setLink(link);
448               n2.setEntityType(txn.getEntityType());
449               n2.setDescriptor(txn.getDescriptor());
450               n2.setOperationType(HttpMethod.GET);
451
452               esWorkOnHand.incrementAndGet();
453
454               supplyAsync(new PerformSearchServiceRetrieval(n2, searchServiceAdapter), esExecutor)
455               .whenComplete((result, error) -> {
456
457                     esWorkOnHand.decrementAndGet();
458
459                     if (error != null) {
460                       LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
461                     } else {
462                       updateElasticSearchCounters(result);
463                       performDocumentUpsert(result, sse);
464                     }
465                   });
466             }
467           }
468         }
469       }
470     } catch (JsonProcessingException exc) {
471         LOG.error(AaiUiMsgs.ERROR_GENERIC, "There was a json processing error while processing the result from elasticsearch. Error: " + exc.getMessage());
472     } catch (IOException exc) {
473         LOG.error(AaiUiMsgs.ERROR_GENERIC, "There was a io processing error while processing the result from elasticsearch. Error: " + exc.getMessage());
474     }
475   }
476
477   protected void populateSuggestionSearchEntityDocument(SuggestionSearchEntity sse, String result,
478       NetworkTransaction txn) throws JsonProcessingException, IOException {
479
480     OxmEntityDescriptor resultDescriptor = txn.getDescriptor();
481
482     sse.setEntityType(resultDescriptor.getEntityName());
483
484     JsonNode entityNode = mapper.readTree(result);
485
486     List<String> primaryKeyValues = new ArrayList<String>();
487     String pkeyValue = null;
488
489     for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
490       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
491       if (pkeyValue != null) {
492         primaryKeyValues.add(pkeyValue);
493       } else {
494         String message = "populateSuggestionSearchEntityDocument(),"
495             + " pKeyValue is null for entityType = " + resultDescriptor.getEntityName();
496         LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
497       }
498     }
499
500     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
501     sse.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
502     sse.generateSuggestionInputPermutations();
503   }
504
505   protected void performDocumentUpsert(NetworkTransaction esGetTxn, SuggestionSearchEntity sse) {
506     /**
507      * <p>
508      * <ul>
509      * As part of the response processing we need to do the following:
510      * <li>1. Extract the version (if present), it will be the ETAG when we use the
511      * Search-Abstraction-Service
512      * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
513      * tag
514      * <li>a) if version is null or RC=404, then standard put, no _update with version tag
515      * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
516      * </ul>
517      * </p>
518      */
519     String link = null;
520     try {
521       link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), sse.getId());
522     } catch (Exception exc) {
523       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
524       return;
525     }
526
527     boolean wasEntryDiscovered = false;
528     if (esGetTxn.getOperationResult().getResultCode() == 404) {
529       LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, sse.getEntityPrimaryKeyValue());
530     } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
531       wasEntryDiscovered = true;
532     } else {
533       /*
534        * Not being a 200 does not mean a failure. eg 201 is returned for created. and 500 for es not
535        * found TODO -> Should we return.
536        */
537       LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
538           String.valueOf(esGetTxn.getOperationResult().getResultCode()));
539       return;
540     }
541     // Insert a new document only if the paylod is different.
542     // This is determined by hashing the payload and using it as a id for the document
543     //
544     if (!wasEntryDiscovered) {
545       try {
546         String jsonPayload = null;
547
548         jsonPayload = sse.getAsJson();
549         if (link != null && jsonPayload != null) {
550
551           NetworkTransaction updateElasticTxn = new NetworkTransaction();
552           updateElasticTxn.setLink(link);
553           updateElasticTxn.setEntityType(esGetTxn.getEntityType());
554           updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
555           updateElasticTxn.setOperationType(HttpMethod.PUT);
556
557           esWorkOnHand.incrementAndGet();
558           supplyAsync(new PerformSearchServicePut(jsonPayload, updateElasticTxn, searchServiceAdapter),
559                   esPutExecutor).whenComplete((result, error) -> {
560
561                 esWorkOnHand.decrementAndGet();
562
563                 if (error != null) {
564                   String message = "Suggestion search entity sync UPDATE PUT error - "
565                       + error.getLocalizedMessage();
566                   LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
567                 } else {
568                   updateElasticSearchCounters(result);
569                   processStoreDocumentResult(result, esGetTxn, sse);
570                 }
571               });
572         }
573       } catch (Exception exc) {
574         String message =
575             "Exception caught during suggestion search entity sync PUT operation. Message - "
576                 + exc.getLocalizedMessage();
577         LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
578       }
579     }
580   }
581
582   private void processStoreDocumentResult(NetworkTransaction esPutResult,
583       NetworkTransaction esGetResult, SuggestionSearchEntity sse) {
584
585     OperationResult or = esPutResult.getOperationResult();
586
587     if (!or.wasSuccessful()) {
588       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
589
590         if (shouldAllowRetry(sse.getId())) {
591           esWorkOnHand.incrementAndGet();
592
593           RetrySuggestionEntitySyncContainer rssec =
594               new RetrySuggestionEntitySyncContainer(esGetResult, sse);
595           retryQueue.push(rssec);
596
597           String message = "Store document failed during suggestion search entity synchronization"
598               + " due to version conflict. Entity will be re-synced.";
599           LOG.warn(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
600         }
601       } else {
602         String message =
603             "Store document failed during suggestion search entity synchronization with result code "
604                 + or.getResultCode() + " and result message " + or.getResult();
605         LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
606       }
607     }
608   }
609
610   /**
611    * Perform retry sync.
612    */
613   private void performRetrySync() {
614     while (retryQueue.peek() != null) {
615
616       RetrySuggestionEntitySyncContainer susc = retryQueue.poll();
617       if (susc != null) {
618
619         SuggestionSearchEntity sus = susc.getSuggestionSearchEntity();
620         NetworkTransaction txn = susc.getNetworkTransaction();
621
622         final Consumer<NetworkTransaction> networkTransactionConsumer = (result) ->  performDocumentUpsert(result, sus);
623         performRetrySync(sus.getId(), networkTransactionConsumer, txn);
624
625       }
626     }
627   }
628
629   /**
630    * Should allow retry.
631    *
632    * @param id the id
633    * @return true, if successful
634    */
635   private boolean shouldAllowRetry(String id) {
636     boolean isRetryAllowed = true;
637     if (retryLimitTracker.get(id) != null) {
638       Integer currentCount = retryLimitTracker.get(id);
639       if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
640         isRetryAllowed = false;
641         String message = "Searchable entity re-sync limit reached for " + id
642             + ", re-sync will no longer be attempted for this entity";
643         LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
644       } else {
645         Integer newCount = new Integer(currentCount.intValue() + 1);
646         retryLimitTracker.put(id, newCount);
647       }
648     } else {
649       Integer firstRetryCount = new Integer(1);
650       retryLimitTracker.put(id, firstRetryCount);
651     }
652
653     return isRetryAllowed;
654   }
655
656
657
658   @Override
659   public SynchronizerState getState() {
660
661     if (!isSyncDone()) {
662       return SynchronizerState.PERFORMING_SYNCHRONIZATION;
663     }
664
665     return SynchronizerState.IDLE;
666
667   }
668
669   /*
670    * (non-Javadoc)
671    * 
672    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
673    */
674   @Override
675   public String getStatReport(boolean showFinalReport) {
676     syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
677     return getStatReport(syncDurationInMs, showFinalReport);
678   }
679
680   /*
681    * (non-Javadoc)
682    * 
683    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
684    */
685   @Override
686   public void shutdown() {
687     this.shutdownExecutors();
688   }
689
690   @Override
691   protected boolean isSyncDone() {
692
693     int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
694
695     if (LOG.isDebugEnabled()) {
696       LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
697           + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
698     }
699
700     if (totalWorkOnHand > 0 || !allWorkEnumerated) {
701       return false;
702     }
703
704     this.syncInProgress = false;
705
706     return true;
707   }
708
709   /*
710    * (non-Javadoc)
711    * 
712    * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
713    */
714   @Override
715   public void clearCache() {
716
717     if (syncInProgress) {
718       LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
719           "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
720       return;
721     }
722
723     super.clearCache();
724     this.resetCounters();
725     if (entityCounters != null) {
726       entityCounters.clear();
727     }
728
729     allWorkEnumerated = false;
730
731   }
732
733 }