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