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