Merge "Fix Blocker/Critical sonar issues"
[aai/sparky-be.git] / src / main / java / org / openecomp / sparky / synchronizer / AutosuggestionSynchronizer.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.openecomp.sparky.synchronizer;
24
25 import static java.util.concurrent.CompletableFuture.supplyAsync;
26
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Deque;
32 import java.util.EnumSet;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.concurrent.ConcurrentHashMap;
38 import java.util.concurrent.ConcurrentLinkedDeque;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.atomic.AtomicInteger;
41 import java.util.function.Supplier;
42
43 import org.openecomp.cl.api.Logger;
44 import org.openecomp.cl.eelf.LoggerFactory;
45 import org.openecomp.cl.mdc.MdcContext;
46 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
47 import org.openecomp.sparky.dal.NetworkTransaction;
48 import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
49 import org.openecomp.sparky.dal.rest.HttpMethod;
50 import org.openecomp.sparky.dal.rest.OperationResult;
51 import org.openecomp.sparky.logging.AaiUiMsgs;
52 import org.openecomp.sparky.synchronizer.config.SynchronizerConfiguration;
53 import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
54 import org.openecomp.sparky.synchronizer.entity.SuggestionSearchEntity;
55 import org.openecomp.sparky.synchronizer.enumeration.OperationState;
56 import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState;
57 import org.openecomp.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
58 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchPut;
59 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchRetrieval;
60 import org.openecomp.sparky.util.NodeUtils;
61 import org.openecomp.sparky.util.SuggestionsPermutation;
62 import org.slf4j.MDC;
63
64 import com.fasterxml.jackson.core.JsonProcessingException;
65 import com.fasterxml.jackson.databind.JsonNode;
66 import com.fasterxml.jackson.databind.node.ArrayNode;
67
68 /**
69  * The Class AutosuggestionSynchronizer.
70  */
71 public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer
72     implements IndexSynchronizer {
73
74   private class RetrySuggestionEntitySyncContainer {
75     NetworkTransaction txn;
76     SuggestionSearchEntity ssec;
77
78     /**
79      * Instantiates a new RetrySuggestionEntitySyncContainer.
80      *
81      * @param txn the txn
82      * @param icer the icer
83      */
84     public RetrySuggestionEntitySyncContainer(NetworkTransaction txn, SuggestionSearchEntity icer) {
85       this.txn = txn;
86       this.ssec = icer;
87     }
88
89     public NetworkTransaction getNetworkTransaction() {
90       return txn;
91     }
92
93     public SuggestionSearchEntity getSuggestionSearchEntity() {
94       return ssec;
95     }
96   }
97
98   private static final Logger LOG =
99       LoggerFactory.getInstance().getLogger(AutosuggestionSynchronizer.class);
100   private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
101
102   private boolean allWorkEnumerated;
103   private Deque<SelfLinkDescriptor> selflinks;
104   private ConcurrentHashMap<String, AtomicInteger> entityCounters;
105   private boolean syncInProgress;
106   private Map<String, String> contextMap;
107   protected ExecutorService esPutExecutor;
108   private Deque<RetrySuggestionEntitySyncContainer> retryQueue;
109   private Map<String, Integer> retryLimitTracker;
110
111   /**
112    * Instantiates a new historical entity summarizer.
113    *
114    * @param indexName the index name
115    * @throws Exception the exception
116    */
117   public AutosuggestionSynchronizer(String indexName) throws Exception {
118     super(LOG, "ASES-" + indexName.toUpperCase(), 2, 5, 5, indexName); // multiple Autosuggestion
119                                                                        // Entity Synchronizer will
120                                                                        // run for different indices
121
122     this.allWorkEnumerated = false;
123     this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
124     this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
125     this.synchronizerName = "Autosuggestion Entity Synchronizer";
126     this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
127     this.syncInProgress = false;
128     this.contextMap = MDC.getCopyOfContextMap();
129     this.esPutExecutor = NodeUtils.createNamedExecutor("SUES-ES-PUT", 5, LOG);
130     this.syncDurationInMs = -1;
131   }
132
133   /**
134    * Collect all the work.
135    *
136    * @return the operation state
137    */
138   private OperationState collectAllTheWork() {
139     final Map<String, String> contextMap = MDC.getCopyOfContextMap();
140     Map<String, OxmEntityDescriptor> descriptorMap =
141         oxmModelLoader.getSuggestionSearchEntityDescriptors();
142
143     if (descriptorMap.isEmpty()) {
144       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
145       LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
146       return OperationState.ERROR;
147     }
148
149     Collection<String> syncTypes = descriptorMap.keySet();
150
151     try {
152
153       /*
154        * launch a parallel async thread to process the documents for each entity-type (to max the of
155        * the configured executor anyway)
156        */
157
158       aaiWorkOnHand.set(syncTypes.size());
159
160       for (String key : syncTypes) {
161
162         supplyAsync(new Supplier<Void>() {
163
164           @Override
165           public Void get() {
166             MDC.setContextMap(contextMap);
167             OperationResult typeLinksResult = null;
168             try {
169               typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
170               aaiWorkOnHand.decrementAndGet();
171               processEntityTypeSelfLinks(typeLinksResult);
172             } catch (Exception exc) {
173               // TODO -> LOG, what should be logged here?
174             }
175
176             return null;
177           }
178
179         }, aaiExecutor).whenComplete((result, error) -> {
180
181           if (error != null) {
182             LOG.error(AaiUiMsgs.ERROR_GENERIC,
183                 "An error occurred getting data from AAI. Error = " + error.getMessage());
184           }
185         });
186
187       }
188
189       while (aaiWorkOnHand.get() != 0) {
190
191         if (LOG.isDebugEnabled()) {
192           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
193         }
194
195         Thread.sleep(1000);
196       }
197
198       aaiWorkOnHand.set(selflinks.size());
199       allWorkEnumerated = true;
200       syncEntityTypes();
201
202       while (!isSyncDone()) {
203         performRetrySync();
204         Thread.sleep(1000);
205       }
206
207       /*
208        * Make sure we don't hang on to retries that failed which could cause issues during future
209        * syncs
210        */
211       retryLimitTracker.clear();
212
213     } catch (Exception exc) {
214       // TODO -> LOG, waht should be logged here?
215     }
216
217     return OperationState.OK;
218
219   }
220
221   /*
222    * (non-Javadoc)
223    * 
224    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
225    */
226   @Override
227   public OperationState doSync() {
228         this.syncDurationInMs = -1;
229         syncStartedTimeStampInMs = System.currentTimeMillis();
230     String txnID = NodeUtils.getRandomTxnId();
231     MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", "");
232     
233     return collectAllTheWork();
234   }
235
236   /**
237    * Process entity type self links.
238    *
239    * @param operationResult the operation result
240    */
241   private void processEntityTypeSelfLinks(OperationResult operationResult) {
242
243     JsonNode rootNode = null;
244
245     final String jsonResult = operationResult.getResult();
246
247     if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
248
249       try {
250         rootNode = mapper.readTree(jsonResult);
251       } catch (IOException exc) {
252         String message = "Could not deserialize JSON (representing operation result) as node tree. "
253             + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
254         LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
255         return;
256       }
257
258       JsonNode resultData = rootNode.get("result-data");
259       ArrayNode resultDataArrayNode = null;
260
261       if (resultData.isArray()) {
262         resultDataArrayNode = (ArrayNode) resultData;
263
264         Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
265         JsonNode element = null;
266
267         while (elementIterator.hasNext()) {
268           element = elementIterator.next();
269
270           final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
271           final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
272
273           OxmEntityDescriptor descriptor = null;
274
275           if (resourceType != null && resourceLink != null) {
276
277             descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
278
279             if (descriptor == null) {
280               LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
281               // go to next element in iterator
282               continue;
283             }
284             selflinks.add(new SelfLinkDescriptor(resourceLink,
285                 SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType));
286
287
288           }
289         }
290       }
291     }
292   }
293
294   /**
295    * Sync entity types.
296    */
297   private void syncEntityTypes() {
298
299     while (selflinks.peek() != null) {
300
301       SelfLinkDescriptor linkDescriptor = selflinks.poll();
302       aaiWorkOnHand.decrementAndGet();
303
304       OxmEntityDescriptor descriptor = null;
305
306       if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
307
308         descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
309
310         if (descriptor == null) {
311           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
312           // go to next element in iterator
313           continue;
314         }
315
316         NetworkTransaction txn = new NetworkTransaction();
317         txn.setDescriptor(descriptor);
318         txn.setLink(linkDescriptor.getSelfLink());
319         txn.setOperationType(HttpMethod.GET);
320         txn.setEntityType(linkDescriptor.getEntityType());
321
322         aaiWorkOnHand.incrementAndGet();
323
324         supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
325             .whenComplete((result, error) -> {
326
327               aaiWorkOnHand.decrementAndGet();
328
329               if (error != null) {
330                 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
331               } else {
332                 if (result == null) {
333                   LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
334                       linkDescriptor.getSelfLink());
335                 } else {
336                   updateActiveInventoryCounters(result);
337                   fetchDocumentForUpsert(result);
338                 }
339               }
340             });
341       }
342
343     }
344
345   }
346   /*
347    * Return a set of valid suggestion attributes for the provided entityName 
348    * that are present in the JSON
349    * @param node    JSON node in which the attributes should be found
350    * @param entityName  Name of the entity
351    * @return List of all valid suggestion attributes(key's)
352    */
353   public List<String> getSuggestionFromReponse(JsonNode node, String entityName) {
354     List<String> suggestableAttr = new ArrayList<String>();
355     HashMap<String, String> desc = oxmModelLoader.getOxmModel().get(entityName);
356     String attr = desc.get("suggestibleAttributes");
357     suggestableAttr = Arrays.asList(attr.split(","));
358     List<String> suggestableValue = new ArrayList<>();
359     for (String attribute : suggestableAttr) {
360       if (node.get(attribute) != null && node.get(attribute).asText().length() > 0) {
361         suggestableValue.add(attribute);
362       }
363     }
364     return suggestableValue;
365   }
366
367   /**
368    * Fetch all the documents for upsert. Based on the number of permutations that are available the
369    * number of documents will be different
370    *
371    * @param txn the txn
372    */
373   private void fetchDocumentForUpsert(NetworkTransaction txn) {
374     if (!txn.getOperationResult().wasSuccessful()) {
375       String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
376       LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
377       return;
378     }
379     try {
380       final String jsonResult = txn.getOperationResult().getResult();
381
382       if (jsonResult != null && jsonResult.length() > 0) {
383
384         // Step 1: Calculate the number of possible permutations of attributes
385         String entityName = txn.getDescriptor().getEntityName();
386         JsonNode entityNode = mapper.readTree(jsonResult);
387
388         SuggestionsPermutation suggPermutation = new SuggestionsPermutation();
389         ArrayList<ArrayList<String>> uniqueLists = suggPermutation
390             .getSuggestionsPermutation(getSuggestionFromReponse(entityNode, entityName));
391
392         // Now we have a list of all possible permutations for the status that are
393         // defined for this entity type. Try inserting a document for every combination.
394         for (ArrayList<String> uniqueList : uniqueLists) {
395           SuggestionSearchEntity sse = new SuggestionSearchEntity(oxmModelLoader);
396           sse.setSuggestableAttr(uniqueList);
397           sse.setPayloadFromResponse(entityNode);
398           sse.setLink(txn.getLink());
399           sse.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink()));
400           populateSuggestionSearchEntityDocument(sse, jsonResult, txn);
401           // The unique id for the document will be created at derive fields
402           sse.deriveFields();
403           // Insert the document only if it has valid statuses
404           if (sse.isSuggestableDoc()) {
405             String link = null;
406             try {
407               link = getElasticFullUrl("/" + sse.getId(), getIndexName());
408             } catch (Exception exc) {
409               LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
410             }
411
412             if (link != null) {
413               NetworkTransaction n2 = new NetworkTransaction();
414               n2.setLink(link);
415               n2.setEntityType(txn.getEntityType());
416               n2.setDescriptor(txn.getDescriptor());
417               n2.setOperationType(HttpMethod.GET);
418
419               esWorkOnHand.incrementAndGet();
420
421               supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor)
422                   .whenComplete((result, error) -> {
423
424                     esWorkOnHand.decrementAndGet();
425
426                     if (error != null) {
427                       LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
428                     } else {
429                       updateElasticSearchCounters(result);
430                       performDocumentUpsert(result, sse);
431                     }
432                   });
433             }
434           }
435         }
436       }
437     } catch (JsonProcessingException exc) {
438       // TODO -> LOG, waht should be logged here?
439     } catch (IOException exc) {
440       // TODO -> LOG, waht should be logged here?
441     }
442   }
443
444   protected void populateSuggestionSearchEntityDocument(SuggestionSearchEntity sse, String result,
445       NetworkTransaction txn) throws JsonProcessingException, IOException {
446
447     OxmEntityDescriptor resultDescriptor = txn.getDescriptor();
448
449     sse.setEntityType(resultDescriptor.getEntityName());
450
451     JsonNode entityNode = mapper.readTree(result);
452
453     List<String> primaryKeyValues = new ArrayList<String>();
454     String pkeyValue = null;
455
456     for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
457       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
458       if (pkeyValue != null) {
459         primaryKeyValues.add(pkeyValue);
460       } else {
461         String message = "populateSuggestionSearchEntityDocument(),"
462             + " pKeyValue is null for entityType = " + resultDescriptor.getEntityName();
463         LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
464       }
465     }
466
467     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
468     sse.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
469     sse.generateSuggestionInputPermutations();
470   }
471
472   protected void performDocumentUpsert(NetworkTransaction esGetTxn, SuggestionSearchEntity sse) {
473     /**
474      * <p>
475      * <ul>
476      * As part of the response processing we need to do the following:
477      * <li>1. Extract the version (if present), it will be the ETAG when we use the
478      * Search-Abstraction-Service
479      * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
480      * tag
481      * <li>a) if version is null or RC=404, then standard put, no _update with version tag
482      * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
483      * </ul>
484      * </p>
485      */
486     String link = null;
487     try {
488       link = getElasticFullUrl("/" + sse.getId(), getIndexName());
489     } catch (Exception exc) {
490       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
491       return;
492     }
493
494     boolean wasEntryDiscovered = false;
495     if (esGetTxn.getOperationResult().getResultCode() == 404) {
496       LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, sse.getEntityPrimaryKeyValue());
497     } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
498       wasEntryDiscovered = true;
499     } else {
500       /*
501        * Not being a 200 does not mean a failure. eg 201 is returned for created. and 500 for es not
502        * found TODO -> Should we return.
503        */
504       LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
505           String.valueOf(esGetTxn.getOperationResult().getResultCode()));
506       return;
507     }
508     // Insert a new document only if the paylod is different.
509     // This is determined by hashing the payload and using it as a id for the document
510     //
511     if (!wasEntryDiscovered) {
512       try {
513         String jsonPayload = null;
514
515         jsonPayload = sse.getIndexDocumentJson();
516         if (link != null && jsonPayload != null) {
517
518           NetworkTransaction updateElasticTxn = new NetworkTransaction();
519           updateElasticTxn.setLink(link);
520           updateElasticTxn.setEntityType(esGetTxn.getEntityType());
521           updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
522           updateElasticTxn.setOperationType(HttpMethod.PUT);
523
524           esWorkOnHand.incrementAndGet();
525           supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
526               esPutExecutor).whenComplete((result, error) -> {
527
528                 esWorkOnHand.decrementAndGet();
529
530                 if (error != null) {
531                   String message = "Suggestion search entity sync UPDATE PUT error - "
532                       + error.getLocalizedMessage();
533                   LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
534                 } else {
535                   updateElasticSearchCounters(result);
536                   processStoreDocumentResult(result, esGetTxn, sse);
537                 }
538               });
539         }
540       } catch (Exception exc) {
541         String message =
542             "Exception caught during suggestion search entity sync PUT operation. Message - "
543                 + exc.getLocalizedMessage();
544         LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
545       }
546     }
547   }
548
549   private void processStoreDocumentResult(NetworkTransaction esPutResult,
550       NetworkTransaction esGetResult, SuggestionSearchEntity sse) {
551
552     OperationResult or = esPutResult.getOperationResult();
553
554     if (!or.wasSuccessful()) {
555       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
556
557         if (shouldAllowRetry(sse.getId())) {
558           esWorkOnHand.incrementAndGet();
559
560           RetrySuggestionEntitySyncContainer rssec =
561               new RetrySuggestionEntitySyncContainer(esGetResult, sse);
562           retryQueue.push(rssec);
563
564           String message = "Store document failed during suggestion search entity synchronization"
565               + " due to version conflict. Entity will be re-synced.";
566           LOG.warn(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
567         }
568       } else {
569         String message =
570             "Store document failed during suggestion search entity synchronization with result code "
571                 + or.getResultCode() + " and result message " + or.getResult();
572         LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
573       }
574     }
575   }
576
577   /**
578    * Perform retry sync.
579    */
580   private void performRetrySync() {
581     while (retryQueue.peek() != null) {
582
583       RetrySuggestionEntitySyncContainer susc = retryQueue.poll();
584       if (susc != null) {
585
586         SuggestionSearchEntity sus = susc.getSuggestionSearchEntity();
587         NetworkTransaction txn = susc.getNetworkTransaction();
588
589         String link = null;
590         try {
591           /*
592            * In this retry flow the se object has already derived its fields
593            */
594           link = getElasticFullUrl("/" + sus.getId(), getIndexName());
595         } catch (Exception exc) {
596           LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
597         }
598
599         if (link != null) {
600           NetworkTransaction retryTransaction = new NetworkTransaction();
601           retryTransaction.setLink(link);
602           retryTransaction.setEntityType(txn.getEntityType());
603           retryTransaction.setDescriptor(txn.getDescriptor());
604           retryTransaction.setOperationType(HttpMethod.GET);
605
606           /*
607            * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
608            * called incrementAndGet when queuing the failed PUT!
609            */
610
611           supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
612               esExecutor).whenComplete((result, error) -> {
613
614                 esWorkOnHand.decrementAndGet();
615
616                 if (error != null) {
617                   LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
618                 } else {
619                   updateElasticSearchCounters(result);
620                   performDocumentUpsert(result, sus);
621                 }
622               });
623         }
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 }