2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.sparky.synchronizer;
25 import static java.util.concurrent.CompletableFuture.supplyAsync;
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;
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;
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;
64 import com.fasterxml.jackson.core.JsonProcessingException;
65 import com.fasterxml.jackson.databind.JsonNode;
66 import com.fasterxml.jackson.databind.node.ArrayNode;
69 * The Class AutosuggestionSynchronizer.
71 public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer
72 implements IndexSynchronizer {
74 private class RetrySuggestionEntitySyncContainer {
75 NetworkTransaction txn;
76 SuggestionSearchEntity ssec;
79 * Instantiates a new RetrySuggestionEntitySyncContainer.
82 * @param icer the icer
84 public RetrySuggestionEntitySyncContainer(NetworkTransaction txn, SuggestionSearchEntity icer) {
89 public NetworkTransaction getNetworkTransaction() {
93 public SuggestionSearchEntity getSuggestionSearchEntity() {
98 private static final Logger LOG =
99 LoggerFactory.getInstance().getLogger(AutosuggestionSynchronizer.class);
100 private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
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;
112 * Instantiates a new historical entity summarizer.
114 * @param indexName the index name
115 * @throws Exception the exception
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
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;
134 * Collect all the work.
136 * @return the operation state
138 private OperationState collectAllTheWork() {
139 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
140 Map<String, OxmEntityDescriptor> descriptorMap =
141 oxmModelLoader.getSuggestionSearchEntityDescriptors();
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;
149 Collection<String> syncTypes = descriptorMap.keySet();
154 * launch a parallel async thread to process the documents for each entity-type (to max the of
155 * the configured executor anyway)
158 aaiWorkOnHand.set(syncTypes.size());
160 for (String key : syncTypes) {
162 supplyAsync(new Supplier<Void>() {
166 MDC.setContextMap(contextMap);
167 OperationResult typeLinksResult = null;
169 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
170 aaiWorkOnHand.decrementAndGet();
171 processEntityTypeSelfLinks(typeLinksResult);
172 } catch (Exception exc) {
173 // TODO -> LOG, what should be logged here?
179 }, aaiExecutor).whenComplete((result, error) -> {
182 LOG.error(AaiUiMsgs.ERROR_GENERIC,
183 "An error occurred getting data from AAI. Error = " + error.getMessage());
189 while (aaiWorkOnHand.get() != 0) {
191 if (LOG.isDebugEnabled()) {
192 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
198 aaiWorkOnHand.set(selflinks.size());
199 allWorkEnumerated = true;
202 while (!isSyncDone()) {
208 * Make sure we don't hang on to retries that failed which could cause issues during future
211 retryLimitTracker.clear();
213 } catch (Exception exc) {
214 // TODO -> LOG, waht should be logged here?
217 return OperationState.OK;
224 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
227 public OperationState doSync() {
228 this.syncDurationInMs = -1;
229 syncStartedTimeStampInMs = System.currentTimeMillis();
230 String txnID = NodeUtils.getRandomTxnId();
231 MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", "");
233 return collectAllTheWork();
237 * Process entity type self links.
239 * @param operationResult the operation result
241 private void processEntityTypeSelfLinks(OperationResult operationResult) {
243 JsonNode rootNode = null;
245 final String jsonResult = operationResult.getResult();
247 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
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);
258 JsonNode resultData = rootNode.get("result-data");
259 ArrayNode resultDataArrayNode = null;
261 if (resultData.isArray()) {
262 resultDataArrayNode = (ArrayNode) resultData;
264 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
265 JsonNode element = null;
267 while (elementIterator.hasNext()) {
268 element = elementIterator.next();
270 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
271 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
273 OxmEntityDescriptor descriptor = null;
275 if (resourceType != null && resourceLink != null) {
277 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
279 if (descriptor == null) {
280 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
281 // go to next element in iterator
284 selflinks.add(new SelfLinkDescriptor(resourceLink,
285 SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType));
297 private void syncEntityTypes() {
299 while (selflinks.peek() != null) {
301 SelfLinkDescriptor linkDescriptor = selflinks.poll();
302 aaiWorkOnHand.decrementAndGet();
304 OxmEntityDescriptor descriptor = null;
306 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
308 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
310 if (descriptor == null) {
311 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
312 // go to next element in iterator
316 NetworkTransaction txn = new NetworkTransaction();
317 txn.setDescriptor(descriptor);
318 txn.setLink(linkDescriptor.getSelfLink());
319 txn.setOperationType(HttpMethod.GET);
320 txn.setEntityType(linkDescriptor.getEntityType());
322 aaiWorkOnHand.incrementAndGet();
324 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
325 .whenComplete((result, error) -> {
327 aaiWorkOnHand.decrementAndGet();
330 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
332 if (result == null) {
333 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
334 linkDescriptor.getSelfLink());
336 updateActiveInventoryCounters(result);
337 fetchDocumentForUpsert(result);
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)
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);
364 return suggestableValue;
368 * Fetch all the documents for upsert. Based on the number of permutations that are available the
369 * number of documents will be different
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);
380 final String jsonResult = txn.getOperationResult().getResult();
382 if (jsonResult != null && jsonResult.length() > 0) {
384 // Step 1: Calculate the number of possible permutations of attributes
385 String entityName = txn.getDescriptor().getEntityName();
386 JsonNode entityNode = mapper.readTree(jsonResult);
388 SuggestionsPermutation suggPermutation = new SuggestionsPermutation();
389 ArrayList<ArrayList<String>> uniqueLists = suggPermutation
390 .getSuggestionsPermutation(getSuggestionFromReponse(entityNode, entityName));
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
403 // Insert the document only if it has valid statuses
404 if (sse.isSuggestableDoc()) {
407 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
408 } catch (Exception exc) {
409 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
413 NetworkTransaction n2 = new NetworkTransaction();
415 n2.setEntityType(txn.getEntityType());
416 n2.setDescriptor(txn.getDescriptor());
417 n2.setOperationType(HttpMethod.GET);
419 esWorkOnHand.incrementAndGet();
421 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor)
422 .whenComplete((result, error) -> {
424 esWorkOnHand.decrementAndGet();
427 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
429 updateElasticSearchCounters(result);
430 performDocumentUpsert(result, sse);
437 } catch (JsonProcessingException exc) {
438 // TODO -> LOG, waht should be logged here?
439 } catch (IOException exc) {
440 // TODO -> LOG, waht should be logged here?
444 protected void populateSuggestionSearchEntityDocument(SuggestionSearchEntity sse, String result,
445 NetworkTransaction txn) throws JsonProcessingException, IOException {
447 OxmEntityDescriptor resultDescriptor = txn.getDescriptor();
449 sse.setEntityType(resultDescriptor.getEntityName());
451 JsonNode entityNode = mapper.readTree(result);
453 List<String> primaryKeyValues = new ArrayList<String>();
454 String pkeyValue = null;
456 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
457 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
458 if (pkeyValue != null) {
459 primaryKeyValues.add(pkeyValue);
461 String message = "populateSuggestionSearchEntityDocument(),"
462 + " pKeyValue is null for entityType = " + resultDescriptor.getEntityName();
463 LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
467 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
468 sse.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
469 sse.generateSuggestionInputPermutations();
472 protected void performDocumentUpsert(NetworkTransaction esGetTxn, SuggestionSearchEntity sse) {
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
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
488 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
489 } catch (Exception exc) {
490 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
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;
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.
504 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
505 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
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
511 if (!wasEntryDiscovered) {
513 String jsonPayload = null;
515 jsonPayload = sse.getIndexDocumentJson();
516 if (link != null && jsonPayload != null) {
518 NetworkTransaction updateElasticTxn = new NetworkTransaction();
519 updateElasticTxn.setLink(link);
520 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
521 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
522 updateElasticTxn.setOperationType(HttpMethod.PUT);
524 esWorkOnHand.incrementAndGet();
525 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
526 esPutExecutor).whenComplete((result, error) -> {
528 esWorkOnHand.decrementAndGet();
531 String message = "Suggestion search entity sync UPDATE PUT error - "
532 + error.getLocalizedMessage();
533 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
535 updateElasticSearchCounters(result);
536 processStoreDocumentResult(result, esGetTxn, sse);
540 } catch (Exception exc) {
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);
549 private void processStoreDocumentResult(NetworkTransaction esPutResult,
550 NetworkTransaction esGetResult, SuggestionSearchEntity sse) {
552 OperationResult or = esPutResult.getOperationResult();
554 if (!or.wasSuccessful()) {
555 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
557 if (shouldAllowRetry(sse.getId())) {
558 esWorkOnHand.incrementAndGet();
560 RetrySuggestionEntitySyncContainer rssec =
561 new RetrySuggestionEntitySyncContainer(esGetResult, sse);
562 retryQueue.push(rssec);
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);
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);
578 * Perform retry sync.
580 private void performRetrySync() {
581 while (retryQueue.peek() != null) {
583 RetrySuggestionEntitySyncContainer susc = retryQueue.poll();
586 SuggestionSearchEntity sus = susc.getSuggestionSearchEntity();
587 NetworkTransaction txn = susc.getNetworkTransaction();
592 * In this retry flow the se object has already derived its fields
594 link = getElasticFullUrl("/" + sus.getId(), getIndexName());
595 } catch (Exception exc) {
596 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
600 NetworkTransaction retryTransaction = new NetworkTransaction();
601 retryTransaction.setLink(link);
602 retryTransaction.setEntityType(txn.getEntityType());
603 retryTransaction.setDescriptor(txn.getDescriptor());
604 retryTransaction.setOperationType(HttpMethod.GET);
607 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
608 * called incrementAndGet when queuing the failed PUT!
611 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
612 esExecutor).whenComplete((result, error) -> {
614 esWorkOnHand.decrementAndGet();
617 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
619 updateElasticSearchCounters(result);
620 performDocumentUpsert(result, sus);
630 * Should allow retry.
633 * @return true, if successful
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);
645 Integer newCount = new Integer(currentCount.intValue() + 1);
646 retryLimitTracker.put(id, newCount);
649 Integer firstRetryCount = new Integer(1);
650 retryLimitTracker.put(id, firstRetryCount);
653 return isRetryAllowed;
659 public SynchronizerState getState() {
662 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
665 return SynchronizerState.IDLE;
672 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
675 public String getStatReport(boolean showFinalReport) {
676 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
677 return getStatReport(syncDurationInMs, showFinalReport);
683 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
686 public void shutdown() {
687 this.shutdownExecutors();
691 protected boolean isSyncDone() {
693 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
695 if (LOG.isDebugEnabled()) {
696 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
697 + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
700 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
704 this.syncInProgress = false;
712 * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
715 public void clearCache() {
717 if (syncInProgress) {
718 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
719 "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
724 this.resetCounters();
725 if (entityCounters != null) {
726 entityCounters.clear();
729 allWorkEnumerated = false;