2 * ============LICENSE_START===================================================
3 * SPARKY (AAI UI service)
4 * ============================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=====================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
26 package org.openecomp.sparky.synchronizer;
28 import static java.util.concurrent.CompletableFuture.supplyAsync;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Deque;
35 import java.util.EnumSet;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.concurrent.ConcurrentHashMap;
41 import java.util.concurrent.ConcurrentLinkedDeque;
42 import java.util.concurrent.ExecutorService;
43 import java.util.concurrent.atomic.AtomicInteger;
44 import java.util.function.Supplier;
46 import org.openecomp.cl.api.Logger;
47 import org.openecomp.cl.eelf.LoggerFactory;
48 import org.openecomp.cl.mdc.MdcContext;
49 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
50 import org.openecomp.sparky.dal.NetworkTransaction;
51 import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
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;
67 import com.fasterxml.jackson.core.JsonProcessingException;
68 import com.fasterxml.jackson.databind.JsonNode;
69 import com.fasterxml.jackson.databind.node.ArrayNode;
72 * The Class AutosuggestionSynchronizer.
74 public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer
75 implements IndexSynchronizer {
77 private class RetrySuggestionEntitySyncContainer {
78 NetworkTransaction txn;
79 SuggestionSearchEntity ssec;
82 * Instantiates a new RetrySuggestionEntitySyncContainer.
85 * @param icer the icer
87 public RetrySuggestionEntitySyncContainer(NetworkTransaction txn, SuggestionSearchEntity icer) {
92 public NetworkTransaction getNetworkTransaction() {
96 public SuggestionSearchEntity getSuggestionSearchEntity() {
101 private static final Logger LOG =
102 LoggerFactory.getInstance().getLogger(AutosuggestionSynchronizer.class);
103 private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
105 private boolean allWorkEnumerated;
106 private Deque<SelfLinkDescriptor> selflinks;
107 private ConcurrentHashMap<String, AtomicInteger> entityCounters;
108 private boolean syncInProgress;
109 private Map<String, String> contextMap;
110 protected ExecutorService esPutExecutor;
111 private Deque<RetrySuggestionEntitySyncContainer> retryQueue;
112 private Map<String, Integer> retryLimitTracker;
115 * Instantiates a new historical entity summarizer.
117 * @param indexName the index name
118 * @throws Exception the exception
120 public AutosuggestionSynchronizer(String indexName) throws Exception {
121 super(LOG, "ASES-" + indexName.toUpperCase(), 2, 5, 5, indexName); // multiple Autosuggestion
122 // Entity Synchronizer will
123 // run for different indices
125 this.allWorkEnumerated = false;
126 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
127 this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
128 this.synchronizerName = "Autosuggestion Entity Synchronizer";
129 this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
130 this.syncInProgress = false;
131 this.contextMap = MDC.getCopyOfContextMap();
132 this.esPutExecutor = NodeUtils.createNamedExecutor("SUES-ES-PUT", 5, LOG);
133 this.syncDurationInMs = -1;
137 * Collect all the work.
139 * @return the operation state
141 private OperationState collectAllTheWork() {
142 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
143 Map<String, OxmEntityDescriptor> descriptorMap =
144 oxmModelLoader.getSuggestionSearchEntityDescriptors();
146 if (descriptorMap.isEmpty()) {
147 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
148 LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES);
149 return OperationState.ERROR;
152 Collection<String> syncTypes = descriptorMap.keySet();
157 * launch a parallel async thread to process the documents for each entity-type (to max the of
158 * the configured executor anyway)
161 aaiWorkOnHand.set(syncTypes.size());
163 for (String key : syncTypes) {
165 supplyAsync(new Supplier<Void>() {
169 MDC.setContextMap(contextMap);
170 OperationResult typeLinksResult = null;
172 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
173 aaiWorkOnHand.decrementAndGet();
174 processEntityTypeSelfLinks(typeLinksResult);
175 } catch (Exception exc) {
176 // TODO -> LOG, what should be logged here?
182 }, aaiExecutor).whenComplete((result, error) -> {
185 LOG.error(AaiUiMsgs.ERROR_GENERIC,
186 "An error occurred getting data from AAI. Error = " + error.getMessage());
192 while (aaiWorkOnHand.get() != 0) {
194 if (LOG.isDebugEnabled()) {
195 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
201 aaiWorkOnHand.set(selflinks.size());
202 allWorkEnumerated = true;
205 while (!isSyncDone()) {
211 * Make sure we don't hang on to retries that failed which could cause issues during future
214 retryLimitTracker.clear();
216 } catch (Exception exc) {
217 // TODO -> LOG, waht should be logged here?
220 return OperationState.OK;
227 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
230 public OperationState doSync() {
231 this.syncDurationInMs = -1;
232 syncStartedTimeStampInMs = System.currentTimeMillis();
233 String txnID = NodeUtils.getRandomTxnId();
234 MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", "");
236 return collectAllTheWork();
240 * Process entity type self links.
242 * @param operationResult the operation result
244 private void processEntityTypeSelfLinks(OperationResult operationResult) {
246 JsonNode rootNode = null;
248 final String jsonResult = operationResult.getResult();
250 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
253 rootNode = mapper.readTree(jsonResult);
254 } catch (IOException exc) {
255 String message = "Could not deserialize JSON (representing operation result) as node tree. "
256 + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
257 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
260 JsonNode resultData = rootNode.get("result-data");
261 ArrayNode resultDataArrayNode = null;
263 if (resultData.isArray()) {
264 resultDataArrayNode = (ArrayNode) resultData;
266 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
267 JsonNode element = null;
269 while (elementIterator.hasNext()) {
270 element = elementIterator.next();
272 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
273 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
275 OxmEntityDescriptor descriptor = null;
277 if (resourceType != null && resourceLink != null) {
279 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
281 if (descriptor == null) {
282 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
283 // go to next element in iterator
286 selflinks.add(new SelfLinkDescriptor(resourceLink,
287 SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType));
299 private void syncEntityTypes() {
301 while (selflinks.peek() != null) {
303 SelfLinkDescriptor linkDescriptor = selflinks.poll();
304 aaiWorkOnHand.decrementAndGet();
306 OxmEntityDescriptor descriptor = null;
308 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
310 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
312 if (descriptor == null) {
313 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
314 // go to next element in iterator
318 NetworkTransaction txn = new NetworkTransaction();
319 txn.setDescriptor(descriptor);
320 txn.setLink(linkDescriptor.getSelfLink());
321 txn.setOperationType(HttpMethod.GET);
322 txn.setEntityType(linkDescriptor.getEntityType());
324 aaiWorkOnHand.incrementAndGet();
326 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
327 .whenComplete((result, error) -> {
329 aaiWorkOnHand.decrementAndGet();
332 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
334 if (result == null) {
335 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
336 linkDescriptor.getSelfLink());
338 updateActiveInventoryCounters(result);
339 fetchDocumentForUpsert(result);
349 * Return a set of valid suggestion attributes for the provided entityName
350 * that are present in the JSON
351 * @param node JSON node in which the attributes should be found
352 * @param entityName Name of the entity
353 * @return List of all valid suggestion attributes(key's)
355 public List<String> getSuggestionFromReponse(JsonNode node, String entityName) {
356 List<String> suggestableAttr = new ArrayList<String>();
357 HashMap<String, String> desc = oxmModelLoader.getOxmModel().get(entityName);
358 String attr = desc.get("suggestibleAttributes");
359 suggestableAttr = Arrays.asList(attr.split(","));
360 List<String> suggestableValue = new ArrayList<>();
361 for (String attribute : suggestableAttr) {
362 if (node.get(attribute) != null && node.get(attribute).asText().length() > 0) {
363 suggestableValue.add(attribute);
366 return suggestableValue;
370 * Fetch all the documents for upsert. Based on the number of permutations that are available the
371 * number of documents will be different
375 private void fetchDocumentForUpsert(NetworkTransaction txn) {
376 if (!txn.getOperationResult().wasSuccessful()) {
377 String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
378 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
382 final String jsonResult = txn.getOperationResult().getResult();
384 if (jsonResult != null && jsonResult.length() > 0) {
386 // Step 1: Calculate the number of possible permutations of attributes
387 String entityName = txn.getDescriptor().getEntityName();
388 JsonNode entityNode = mapper.readTree(jsonResult);
390 SuggestionsPermutation suggPermutation = new SuggestionsPermutation();
391 ArrayList<ArrayList<String>> uniqueLists = suggPermutation
392 .getSuggestionsPermutation(getSuggestionFromReponse(entityNode, entityName));
394 // Now we have a list of all possible permutations for the status that are
395 // defined for this entity type. Try inserting a document for every combination.
396 for (ArrayList<String> uniqueList : uniqueLists) {
397 SuggestionSearchEntity sse = new SuggestionSearchEntity(oxmModelLoader);
398 sse.setSuggestableAttr(uniqueList);
399 sse.setPayloadFromResponse(entityNode);
400 sse.setLink(txn.getLink());
401 sse.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink()));
402 populateSuggestionSearchEntityDocument(sse, jsonResult, txn);
403 // The unique id for the document will be created at derive fields
405 // Insert the document only if it has valid statuses
406 if (sse.isSuggestableDoc()) {
409 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
410 } catch (Exception exc) {
411 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
415 NetworkTransaction n2 = new NetworkTransaction();
417 n2.setEntityType(txn.getEntityType());
418 n2.setDescriptor(txn.getDescriptor());
419 n2.setOperationType(HttpMethod.GET);
421 esWorkOnHand.incrementAndGet();
423 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor)
424 .whenComplete((result, error) -> {
426 esWorkOnHand.decrementAndGet();
429 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
431 updateElasticSearchCounters(result);
432 performDocumentUpsert(result, sse);
439 } catch (JsonProcessingException exc) {
440 // TODO -> LOG, waht should be logged here?
441 } catch (IOException exc) {
442 // TODO -> LOG, waht should be logged here?
446 protected void populateSuggestionSearchEntityDocument(SuggestionSearchEntity sse, String result,
447 NetworkTransaction txn) throws JsonProcessingException, IOException {
449 OxmEntityDescriptor resultDescriptor = txn.getDescriptor();
451 sse.setEntityType(resultDescriptor.getEntityName());
453 JsonNode entityNode = mapper.readTree(result);
455 List<String> primaryKeyValues = new ArrayList<String>();
456 String pkeyValue = null;
458 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
459 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
460 if (pkeyValue != null) {
461 primaryKeyValues.add(pkeyValue);
463 String message = "populateSuggestionSearchEntityDocument(),"
464 + " pKeyValue is null for entityType = " + resultDescriptor.getEntityName();
465 LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
469 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
470 sse.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
471 sse.generateSuggestionInputPermutations();
474 protected void performDocumentUpsert(NetworkTransaction esGetTxn, SuggestionSearchEntity sse) {
478 * As part of the response processing we need to do the following:
479 * <li>1. Extract the version (if present), it will be the ETAG when we use the
480 * Search-Abstraction-Service
481 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
483 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
484 * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
490 link = getElasticFullUrl("/" + sse.getId(), getIndexName());
491 } catch (Exception exc) {
492 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
496 boolean wasEntryDiscovered = false;
497 if (esGetTxn.getOperationResult().getResultCode() == 404) {
498 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, sse.getEntityPrimaryKeyValue());
499 } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
500 wasEntryDiscovered = true;
503 * Not being a 200 does not mean a failure. eg 201 is returned for created. and 500 for es not
504 * found TODO -> Should we return.
506 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
507 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
510 // Insert a new document only if the paylod is different.
511 // This is determined by hashing the payload and using it as a id for the document
513 if (!wasEntryDiscovered) {
515 String jsonPayload = null;
517 jsonPayload = sse.getIndexDocumentJson();
518 if (link != null && jsonPayload != null) {
520 NetworkTransaction updateElasticTxn = new NetworkTransaction();
521 updateElasticTxn.setLink(link);
522 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
523 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
524 updateElasticTxn.setOperationType(HttpMethod.PUT);
526 esWorkOnHand.incrementAndGet();
527 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
528 esPutExecutor).whenComplete((result, error) -> {
530 esWorkOnHand.decrementAndGet();
533 String message = "Suggestion search entity sync UPDATE PUT error - "
534 + error.getLocalizedMessage();
535 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
537 updateElasticSearchCounters(result);
538 processStoreDocumentResult(result, esGetTxn, sse);
542 } catch (Exception exc) {
544 "Exception caught during suggestion search entity sync PUT operation. Message - "
545 + exc.getLocalizedMessage();
546 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
551 private void processStoreDocumentResult(NetworkTransaction esPutResult,
552 NetworkTransaction esGetResult, SuggestionSearchEntity sse) {
554 OperationResult or = esPutResult.getOperationResult();
556 if (!or.wasSuccessful()) {
557 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
559 if (shouldAllowRetry(sse.getId())) {
560 esWorkOnHand.incrementAndGet();
562 RetrySuggestionEntitySyncContainer rssec =
563 new RetrySuggestionEntitySyncContainer(esGetResult, sse);
564 retryQueue.push(rssec);
566 String message = "Store document failed during suggestion search entity synchronization"
567 + " due to version conflict. Entity will be re-synced.";
568 LOG.warn(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
572 "Store document failed during suggestion search entity synchronization with result code "
573 + or.getResultCode() + " and result message " + or.getResult();
574 LOG.error(AaiUiMsgs.ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, message);
580 * Perform retry sync.
582 private void performRetrySync() {
583 while (retryQueue.peek() != null) {
585 RetrySuggestionEntitySyncContainer susc = retryQueue.poll();
588 SuggestionSearchEntity sus = susc.getSuggestionSearchEntity();
589 NetworkTransaction txn = susc.getNetworkTransaction();
594 * In this retry flow the se object has already derived its fields
596 link = getElasticFullUrl("/" + sus.getId(), getIndexName());
597 } catch (Exception exc) {
598 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
602 NetworkTransaction retryTransaction = new NetworkTransaction();
603 retryTransaction.setLink(link);
604 retryTransaction.setEntityType(txn.getEntityType());
605 retryTransaction.setDescriptor(txn.getDescriptor());
606 retryTransaction.setOperationType(HttpMethod.GET);
609 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
610 * called incrementAndGet when queuing the failed PUT!
613 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
614 esExecutor).whenComplete((result, error) -> {
616 esWorkOnHand.decrementAndGet();
619 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
621 updateElasticSearchCounters(result);
622 performDocumentUpsert(result, sus);
632 * Should allow retry.
635 * @return true, if successful
637 private boolean shouldAllowRetry(String id) {
638 boolean isRetryAllowed = true;
639 if (retryLimitTracker.get(id) != null) {
640 Integer currentCount = retryLimitTracker.get(id);
641 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
642 isRetryAllowed = false;
643 String message = "Searchable entity re-sync limit reached for " + id
644 + ", re-sync will no longer be attempted for this entity";
645 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
647 Integer newCount = new Integer(currentCount.intValue() + 1);
648 retryLimitTracker.put(id, newCount);
651 Integer firstRetryCount = new Integer(1);
652 retryLimitTracker.put(id, firstRetryCount);
655 return isRetryAllowed;
661 public SynchronizerState getState() {
664 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
667 return SynchronizerState.IDLE;
674 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
677 public String getStatReport(boolean showFinalReport) {
678 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
679 return getStatReport(syncDurationInMs, showFinalReport);
685 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
688 public void shutdown() {
689 this.shutdownExecutors();
693 protected boolean isSyncDone() {
695 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
697 if (LOG.isDebugEnabled()) {
698 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
699 + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
702 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
706 this.syncInProgress = false;
714 * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
717 public void clearCache() {
719 if (syncInProgress) {
720 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
721 "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
726 this.resetCounters();
727 if (entityCounters != null) {
728 entityCounters.clear();
731 allWorkEnumerated = false;