2 * ============LICENSE_START=======================================================
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
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 package org.onap.aai.sparky.aggregation.sync;
23 import static java.util.concurrent.CompletableFuture.supplyAsync;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Deque;
28 import java.util.EnumSet;
29 import java.util.Iterator;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentLinkedDeque;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.function.Consumer;
36 import java.util.function.Supplier;
38 import org.onap.aai.cl.api.Logger;
39 import org.onap.aai.cl.eelf.LoggerFactory;
40 import org.onap.aai.cl.mdc.MdcContext;
41 import org.onap.aai.restclient.client.OperationResult;
42 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
43 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
44 import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
45 import org.onap.aai.sparky.dal.NetworkTransaction;
46 import org.onap.aai.sparky.dal.rest.HttpMethod;
47 import org.onap.aai.sparky.logging.AaiUiMsgs;
48 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
49 import org.onap.aai.sparky.sync.IndexSynchronizer;
50 import org.onap.aai.sparky.sync.SynchronizerConstants;
51 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
52 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
53 import org.onap.aai.sparky.sync.entity.AggregationEntity;
54 import org.onap.aai.sparky.sync.entity.MergableEntity;
55 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
56 import org.onap.aai.sparky.sync.enumeration.OperationState;
57 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
58 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
59 import org.onap.aai.sparky.sync.task.PerformSearchServicePut;
60 import org.onap.aai.sparky.sync.task.PerformSearchServiceRetrieval;
61 import org.onap.aai.sparky.sync.task.PerformSearchServiceUpdate;
62 import org.onap.aai.sparky.util.NodeUtils;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.JsonNode;
67 import com.fasterxml.jackson.databind.ObjectReader;
68 import com.fasterxml.jackson.databind.node.ArrayNode;
71 * The Class AutosuggestionSynchronizer.
73 public class AggregationSynchronizer extends AbstractEntitySynchronizer
74 implements IndexSynchronizer {
77 * The Class RetryAggregationEntitySyncContainer.
79 private class RetryAggregationEntitySyncContainer {
80 NetworkTransaction txn;
84 * Instantiates a new retry aggregation entity sync container.
89 public RetryAggregationEntitySyncContainer(NetworkTransaction txn, AggregationEntity ae) {
94 public NetworkTransaction getNetworkTransaction() {
98 public AggregationEntity getAggregationEntity() {
103 private static final Logger LOG =
104 LoggerFactory.getInstance().getLogger(AggregationSynchronizer.class);
105 private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
107 private boolean allWorkEnumerated;
108 private Deque<SelfLinkDescriptor> selflinks;
109 private Deque<RetryAggregationEntitySyncContainer> retryQueue;
110 private Map<String, Integer> retryLimitTracker;
111 protected ExecutorService esPutExecutor;
112 private ConcurrentHashMap<String, AtomicInteger> entityCounters;
113 private boolean syncInProgress;
114 private Map<String, String> contextMap;
115 private String entityType;
116 private ElasticSearchSchemaConfig schemaConfig;
117 private OxmEntityLookup oxmEntityLookup;
120 * Instantiates a new entity aggregation synchronizer.
122 * @throws Exception the exception
124 public AggregationSynchronizer(String entityType, ElasticSearchSchemaConfig schemaConfig,
125 int numSyncWorkers, int numActiveInventoryWorkers, int numElasticWorkers,
126 NetworkStatisticsConfig aaiStatConfig, NetworkStatisticsConfig esStatConfig,
127 OxmEntityLookup oxmEntityLookup) throws Exception {
129 super(LOG, "AGGES-" + schemaConfig.getIndexName().toUpperCase(), numSyncWorkers,
130 numActiveInventoryWorkers, numElasticWorkers, schemaConfig.getIndexName(),aaiStatConfig, esStatConfig);
132 this.oxmEntityLookup = oxmEntityLookup;
134 this.schemaConfig = schemaConfig;
135 this.entityType = entityType;
136 this.allWorkEnumerated = false;
137 this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
138 this.synchronizerName = "Entity Aggregation Synchronizer";
139 this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
140 this.syncInProgress = false;
141 this.allWorkEnumerated = false;
142 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
143 this.retryQueue = new ConcurrentLinkedDeque<RetryAggregationEntitySyncContainer>();
144 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
146 this.esPutExecutor = NodeUtils.createNamedExecutor("AGGES-ES-PUT", 1, LOG);
148 this.aaiEntityStats.intializeEntityCounters(entityType);
149 this.esEntityStats.intializeEntityCounters(entityType);
151 this.contextMap = MDC.getCopyOfContextMap();
155 * Collect all the work.
157 * @return the operation state
159 private OperationState collectAllTheWork() {
160 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
161 final String entity = this.getEntityType();
164 aaiWorkOnHand.set(1);
166 supplyAsync(new Supplier<Void>() {
170 MDC.setContextMap(contextMap);
171 OperationResult typeLinksResult = null;
173 typeLinksResult = aaiAdapter.getSelfLinksByEntityType(entity);
174 aaiWorkOnHand.decrementAndGet();
175 processEntityTypeSelfLinks(typeLinksResult);
176 } catch (Exception exc) {
177 LOG.error(AaiUiMsgs.ERROR_GENERIC, "Processing execption while building working set. Error:"
184 }, aaiExecutor).whenComplete((result, error) -> {
187 LOG.error(AaiUiMsgs.ERROR_GENERIC,
188 "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;
225 * Perform retry sync.
227 private void performRetrySync() {
228 while (retryQueue.peek() != null) {
230 RetryAggregationEntitySyncContainer rsc = retryQueue.poll();
233 AggregationEntity ae = rsc.getAggregationEntity();
234 NetworkTransaction txn = rsc.getNetworkTransaction();
236 final Consumer<NetworkTransaction> networkTransactionConsumer = (result) -> performDocumentUpsert(result, ae);
237 performRetrySync(ae.getId(), networkTransactionConsumer, txn);
245 * Perform document upsert.
247 * @param esGetTxn the es get txn
250 protected void performDocumentUpsert(NetworkTransaction esGetTxn, AggregationEntity ae) {
254 * As part of the response processing we need to do the following:
255 * <li>1. Extract the version (if present), it will be the ETAG when we use the
256 * Search-Abstraction-Service
257 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
259 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
260 * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
266 link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), ae.getId());
267 } catch (Exception exc) {
268 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
272 String versionNumber = null;
273 boolean wasEntryDiscovered = false;
274 if (esGetTxn.getOperationResult().getResultCode() == 404) {
275 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, ae.getEntityPrimaryKeyValue());
276 } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
277 wasEntryDiscovered = true;
279 versionNumber = NodeUtils.extractFieldValueFromObject(
280 NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
282 } catch (IOException exc) {
284 "Error extracting version number from response, aborting aggregation entity sync of "
285 + ae.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
286 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
291 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
294 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
295 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
300 String jsonPayload = null;
301 if (wasEntryDiscovered) {
303 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
304 NodeUtils.extractObjectsByKey(
305 NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
306 "_source", sourceObject);
308 if (!sourceObject.isEmpty()) {
309 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
310 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
311 ObjectReader updater = mapper.readerForUpdating(me);
312 MergableEntity merged = updater.readValue(ae.getAsJson());
313 jsonPayload = mapper.writeValueAsString(merged);
315 } catch (IOException exc) {
317 "Error extracting source value from response, aborting aggregation entity sync of "
318 + ae.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
319 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
323 jsonPayload = ae.getAsJson();
326 if (wasEntryDiscovered) {
327 if (versionNumber != null && jsonPayload != null) {
329 String requestPayload =
330 searchServiceAdapter.buildBulkImportOperationRequest(schemaConfig.getIndexName(),
331 ae.getId(),jsonPayload);
333 NetworkTransaction transactionTracker = new NetworkTransaction();
334 transactionTracker.setEntityType(esGetTxn.getEntityType());
335 transactionTracker.setDescriptor(esGetTxn.getDescriptor());
336 transactionTracker.setOperationType(HttpMethod.PUT);
338 esWorkOnHand.incrementAndGet();
339 supplyAsync(new PerformSearchServiceUpdate(searchServiceAdapter.buildSearchServiceBulkUrl(),
340 requestPayload, searchServiceAdapter, transactionTracker), esPutExecutor)
341 .whenComplete((result, error) -> {
343 esWorkOnHand.decrementAndGet();
346 String message = "Aggregation entity sync UPDATE PUT error - "
347 + error.getLocalizedMessage();
348 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
350 updateElasticSearchCounters(result);
351 processStoreDocumentResult(result, esGetTxn, ae);
357 if (link != null && jsonPayload != null) {
359 NetworkTransaction updateElasticTxn = new NetworkTransaction();
360 updateElasticTxn.setLink(link);
361 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
362 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
363 updateElasticTxn.setOperationType(HttpMethod.PUT);
365 esWorkOnHand.incrementAndGet();
366 supplyAsync(new PerformSearchServicePut(jsonPayload, updateElasticTxn, searchServiceAdapter),
367 esPutExecutor).whenComplete((result, error) -> {
369 esWorkOnHand.decrementAndGet();
373 "Aggregation entity sync UPDATE PUT error - " + error.getLocalizedMessage();
374 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
376 updateElasticSearchCounters(result);
377 processStoreDocumentResult(result, esGetTxn, ae);
382 } catch (Exception exc) {
383 String message = "Exception caught during aggregation entity sync PUT operation. Message - "
384 + exc.getLocalizedMessage();
385 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
390 * Should allow retry.
393 * @return true, if successful
395 private boolean shouldAllowRetry(String id) {
396 boolean isRetryAllowed = true;
397 if (retryLimitTracker.get(id) != null) {
398 Integer currentCount = retryLimitTracker.get(id);
399 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
400 isRetryAllowed = false;
401 String message = "Aggregation entity re-sync limit reached for " + id
402 + ", re-sync will no longer be attempted for this entity";
403 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
405 Integer newCount = new Integer(currentCount.intValue() + 1);
406 retryLimitTracker.put(id, newCount);
409 Integer firstRetryCount = new Integer(1);
410 retryLimitTracker.put(id, firstRetryCount);
413 return isRetryAllowed;
417 * Process store document result.
419 * @param esPutResult the es put result
420 * @param esGetResult the es get result
423 private void processStoreDocumentResult(NetworkTransaction esPutResult,
424 NetworkTransaction esGetResult, AggregationEntity ae) {
426 OperationResult or = esPutResult.getOperationResult();
428 if (!or.wasSuccessful()) {
429 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
431 if (shouldAllowRetry(ae.getId())) {
432 esWorkOnHand.incrementAndGet();
434 RetryAggregationEntitySyncContainer rsc =
435 new RetryAggregationEntitySyncContainer(esGetResult, ae);
436 retryQueue.push(rsc);
438 String message = "Store document failed during aggregation entity synchronization"
439 + " due to version conflict. Entity will be re-synced.";
440 LOG.warn(AaiUiMsgs.ERROR_GENERIC, message);
444 "Store document failed during aggregation entity synchronization with result code "
445 + or.getResultCode() + " and result message " + or.getResult();
446 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
454 private void syncEntityTypes() {
456 while (selflinks.peek() != null) {
458 SelfLinkDescriptor linkDescriptor = selflinks.poll();
459 aaiWorkOnHand.decrementAndGet();
461 OxmEntityDescriptor descriptor = null;
463 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
465 descriptor = oxmEntityLookup.getEntityDescriptors().get(linkDescriptor.getEntityType());
467 if (descriptor == null) {
468 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
469 // go to next element in iterator
473 NetworkTransaction txn = new NetworkTransaction();
474 txn.setDescriptor(descriptor);
475 txn.setLink(linkDescriptor.getSelfLink());
476 txn.setOperationType(HttpMethod.GET);
477 txn.setEntityType(linkDescriptor.getEntityType());
479 aaiWorkOnHand.incrementAndGet();
481 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter,"sync"), aaiExecutor)
482 .whenComplete((result, error) -> {
484 aaiWorkOnHand.decrementAndGet();
487 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
489 if (result == null) {
490 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
491 linkDescriptor.getSelfLink());
493 updateActiveInventoryCounters(result);
494 fetchDocumentForUpsert(result);
505 * Fetch document for upsert.
509 private void fetchDocumentForUpsert(NetworkTransaction txn) {
511 if (!txn.getOperationResult().wasSuccessful()) {
512 String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
513 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
518 final String jsonResult = txn.getOperationResult().getResult();
519 if (jsonResult != null && jsonResult.length() > 0) {
521 AggregationEntity ae = new AggregationEntity();
522 ae.setLink(ActiveInventoryAdapter.extractResourcePath(txn.getLink()));
523 populateAggregationEntityDocument(ae, jsonResult, txn.getDescriptor());
528 link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), ae.getId());
529 } catch (Exception exc) {
530 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
534 NetworkTransaction n2 = new NetworkTransaction();
536 n2.setEntityType(txn.getEntityType());
537 n2.setDescriptor(txn.getDescriptor());
538 n2.setOperationType(HttpMethod.GET);
540 esWorkOnHand.incrementAndGet();
542 supplyAsync(new PerformSearchServiceRetrieval(n2, searchServiceAdapter), esExecutor)
543 .whenComplete((result, error) -> {
545 esWorkOnHand.decrementAndGet();
548 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
550 updateElasticSearchCounters(result);
551 performDocumentUpsert(result, ae);
557 } catch (JsonProcessingException exc) {
558 LOG.error(AaiUiMsgs.ERROR_GENERIC,
559 "There was a JSON processing error fetching the elastic document for upsert. Error: "
561 } catch (IOException exc) {
562 LOG.error(AaiUiMsgs.ERROR_GENERIC,
563 "There was an IO error fetching the elastic document for upsert. Error: " + exc.getMessage());
569 * Populate aggregation entity document.
572 * @param result the result
573 * @param resultDescriptor the result descriptor
574 * @throws JsonProcessingException the json processing exception
575 * @throws IOException Signals that an I/O exception has occurred.
577 protected void populateAggregationEntityDocument(AggregationEntity doc, String result,
578 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
579 doc.setEntityType(resultDescriptor.getEntityName());
580 JsonNode entityNode = mapper.readTree(result);
581 Map<String, Object> map = mapper.convertValue(entityNode, Map.class);
582 doc.copyAttributeKeyValuePair(map);
586 * Process entity type self links.
588 * @param operationResult the operation result
590 private void processEntityTypeSelfLinks(OperationResult operationResult) {
592 if (operationResult == null) {
596 final String jsonResult = operationResult.getResult();
598 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
601 JsonNode rootNode = mapper.readTree(jsonResult);
603 JsonNode resultData = rootNode.get("result-data");
605 if (resultData.isArray()) {
606 ArrayNode resultDataArrayNode = (ArrayNode) resultData;
608 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
610 while (elementIterator.hasNext()) {
611 JsonNode element = elementIterator.next();
613 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
614 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
616 if (resourceType != null && resourceLink != null) {
618 OxmEntityDescriptor descriptor = oxmEntityLookup.getEntityDescriptors().get(resourceType);
620 if (descriptor == null) {
621 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
622 // go to next element in iterator
626 selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
631 } catch (IOException exc) {
633 "Could not deserialize JSON (representing operation result) as node tree. " +
634 "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
635 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
644 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
647 public OperationState doSync() {
648 this.syncDurationInMs = -1;
649 syncStartedTimeStampInMs = System.currentTimeMillis();
650 String txnID = NodeUtils.getRandomTxnId();
651 MdcContext.initialize(txnID, "AggregationSynchronizer", "", "Sync", "");
653 return collectAllTheWork();
657 public SynchronizerState getState() {
660 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
663 return SynchronizerState.IDLE;
670 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
673 public String getStatReport(boolean showFinalReport) {
674 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
675 return getStatReport(syncDurationInMs, showFinalReport);
678 public String getEntityType() {
682 public void setEntityType(String entityType) {
683 this.entityType = entityType;
689 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
692 public void shutdown() {
693 this.shutdownExecutors();
697 protected boolean isSyncDone() {
699 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
701 if (LOG.isDebugEnabled()) {
702 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
703 + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
706 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
710 this.syncInProgress = false;
718 * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
721 public void clearCache() {
723 if (syncInProgress) {
724 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
725 "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
730 this.resetCounters();
731 if (entityCounters != null) {
732 entityCounters.clear();
735 allWorkEnumerated = false;