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 AggregationSynchronizer.
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();
215 } catch (InterruptedException e) {
216 // Restore interrupted state...
217 Thread.currentThread().interrupt();
218 } catch (Exception exc) {
219 // TODO -> LOG, waht should be logged here?
222 return OperationState.OK;
227 * Perform retry sync.
229 private void performRetrySync() {
230 while (retryQueue.peek() != null) {
232 RetryAggregationEntitySyncContainer rsc = retryQueue.poll();
235 AggregationEntity ae = rsc.getAggregationEntity();
236 NetworkTransaction txn = rsc.getNetworkTransaction();
238 final Consumer<NetworkTransaction> networkTransactionConsumer = (result) -> performDocumentUpsert(result, ae);
239 performRetrySync(ae.getId(), networkTransactionConsumer, txn);
247 * Perform document upsert.
249 * @param esGetTxn the es get txn
252 protected void performDocumentUpsert(NetworkTransaction esGetTxn, AggregationEntity ae) {
256 * As part of the response processing we need to do the following:
257 * <li>1. Extract the version (if present), it will be the ETAG when we use the
258 * Search-Abstraction-Service
259 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
261 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
262 * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
268 link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), ae.getId());
269 } catch (Exception exc) {
270 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
274 String versionNumber = null;
275 boolean wasEntryDiscovered = false;
276 if (esGetTxn.getOperationResult().getResultCode() == 404) {
277 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, ae.getEntityPrimaryKeyValue());
278 } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
279 wasEntryDiscovered = true;
281 versionNumber = NodeUtils.extractFieldValueFromObject(
282 NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
284 } catch (IOException exc) {
286 "Error extracting version number from response, aborting aggregation entity sync of "
287 + ae.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
288 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
293 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
296 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
297 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
302 String jsonPayload = null;
303 if (wasEntryDiscovered) {
305 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
306 NodeUtils.extractObjectsByKey(
307 NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
308 "content", sourceObject);
310 if (!sourceObject.isEmpty()) {
311 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
312 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
313 ObjectReader updater = mapper.readerForUpdating(me);
314 MergableEntity merged = updater.readValue(ae.getAsJson());
315 jsonPayload = mapper.writeValueAsString(merged);
317 } catch (IOException exc) {
319 "Error extracting source value from response, aborting aggregation entity sync of "
320 + ae.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
321 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
325 jsonPayload = ae.getAsJson();
328 if (wasEntryDiscovered) {
329 if (versionNumber != null && jsonPayload != null) {
331 String requestPayload =
332 searchServiceAdapter.buildBulkImportOperationRequest(schemaConfig.getIndexName(),
333 versionNumber, ae.getId(),jsonPayload);
335 NetworkTransaction transactionTracker = new NetworkTransaction();
336 transactionTracker.setEntityType(esGetTxn.getEntityType());
337 transactionTracker.setDescriptor(esGetTxn.getDescriptor());
338 transactionTracker.setOperationType(HttpMethod.PUT);
340 esWorkOnHand.incrementAndGet();
341 supplyAsync(new PerformSearchServiceUpdate(searchServiceAdapter.buildSearchServiceBulkUrl(),
342 requestPayload, searchServiceAdapter, transactionTracker), esPutExecutor)
343 .whenComplete((result, error) -> {
345 esWorkOnHand.decrementAndGet();
348 String message = "Aggregation entity sync UPDATE PUT error - "
349 + error.getLocalizedMessage();
350 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
352 updateElasticSearchCounters(result);
353 processStoreDocumentResult(result, esGetTxn, ae);
359 if (link != null && jsonPayload != null) {
361 NetworkTransaction updateElasticTxn = new NetworkTransaction();
362 updateElasticTxn.setLink(link);
363 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
364 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
365 updateElasticTxn.setOperationType(HttpMethod.PUT);
367 esWorkOnHand.incrementAndGet();
368 supplyAsync(new PerformSearchServicePut(jsonPayload, updateElasticTxn, searchServiceAdapter),
369 esPutExecutor).whenComplete((result, error) -> {
371 esWorkOnHand.decrementAndGet();
375 "Aggregation entity sync UPDATE PUT error - " + error.getLocalizedMessage();
376 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
378 updateElasticSearchCounters(result);
379 processStoreDocumentResult(result, esGetTxn, ae);
384 } catch (Exception exc) {
385 String message = "Exception caught during aggregation entity sync PUT operation. Message - "
386 + exc.getLocalizedMessage();
387 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
392 * Should allow retry.
395 * @return true, if successful
397 private boolean shouldAllowRetry(String id) {
398 boolean isRetryAllowed = true;
399 if (retryLimitTracker.get(id) != null) {
400 Integer currentCount = retryLimitTracker.get(id);
401 if (currentCount >= RETRY_COUNT_PER_ENTITY_LIMIT) {
402 isRetryAllowed = false;
403 String message = "Aggregation entity re-sync limit reached for " + id
404 + ", re-sync will no longer be attempted for this entity";
405 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
407 Integer newCount = currentCount + 1;
408 retryLimitTracker.put(id, newCount);
411 Integer firstRetryCount = 1;
412 retryLimitTracker.put(id, firstRetryCount);
415 return isRetryAllowed;
419 * Process store document result.
421 * @param esPutResult the es put result
422 * @param esGetResult the es get result
425 private void processStoreDocumentResult(NetworkTransaction esPutResult,
426 NetworkTransaction esGetResult, AggregationEntity ae) {
428 OperationResult or = esPutResult.getOperationResult();
430 if (!or.wasSuccessful()) {
431 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
433 if (shouldAllowRetry(ae.getId())) {
434 esWorkOnHand.incrementAndGet();
436 RetryAggregationEntitySyncContainer rsc =
437 new RetryAggregationEntitySyncContainer(esGetResult, ae);
438 retryQueue.push(rsc);
440 String message = "Store document failed during aggregation entity synchronization"
441 + " due to version conflict. Entity will be re-synced.";
442 LOG.warn(AaiUiMsgs.ERROR_GENERIC, message);
446 "Store document failed during aggregation entity synchronization with result code "
447 + or.getResultCode() + " and result message " + or.getResult();
448 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
456 private void syncEntityTypes() {
458 while (selflinks.peek() != null) {
460 SelfLinkDescriptor linkDescriptor = selflinks.poll();
461 aaiWorkOnHand.decrementAndGet();
463 OxmEntityDescriptor descriptor = null;
465 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
467 descriptor = oxmEntityLookup.getEntityDescriptors().get(linkDescriptor.getEntityType());
469 if (descriptor == null) {
470 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
471 // go to next element in iterator
475 NetworkTransaction txn = new NetworkTransaction();
476 txn.setDescriptor(descriptor);
477 txn.setLink(linkDescriptor.getSelfLink());
478 txn.setOperationType(HttpMethod.GET);
479 txn.setEntityType(linkDescriptor.getEntityType());
481 aaiWorkOnHand.incrementAndGet();
483 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter,"sync"), aaiExecutor)
484 .whenComplete((result, error) -> {
486 aaiWorkOnHand.decrementAndGet();
489 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
491 if (result == null) {
492 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
493 linkDescriptor.getSelfLink());
495 updateActiveInventoryCounters(result);
496 fetchDocumentForUpsert(result);
507 * Fetch document for upsert.
511 private void fetchDocumentForUpsert(NetworkTransaction txn) {
513 if (!txn.getOperationResult().wasSuccessful()) {
514 String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
515 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
520 final String jsonResult = txn.getOperationResult().getResult();
521 if (jsonResult != null && jsonResult.length() > 0) {
523 AggregationEntity ae = new AggregationEntity();
524 ae.setLink(ActiveInventoryAdapter.extractResourcePath(txn.getLink()));
525 populateAggregationEntityDocument(ae, jsonResult, txn.getDescriptor());
530 link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), ae.getId());
531 } catch (Exception exc) {
532 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
536 NetworkTransaction n2 = new NetworkTransaction();
538 n2.setEntityType(txn.getEntityType());
539 n2.setDescriptor(txn.getDescriptor());
540 n2.setOperationType(HttpMethod.GET);
542 esWorkOnHand.incrementAndGet();
544 supplyAsync(new PerformSearchServiceRetrieval(n2, searchServiceAdapter), esExecutor)
545 .whenComplete((result, error) -> {
547 esWorkOnHand.decrementAndGet();
550 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
552 updateElasticSearchCounters(result);
553 performDocumentUpsert(result, ae);
559 } catch (JsonProcessingException exc) {
560 LOG.error(AaiUiMsgs.ERROR_GENERIC,
561 "There was a JSON processing error fetching the elastic document for upsert. Error: "
563 } catch (IOException exc) {
564 LOG.error(AaiUiMsgs.ERROR_GENERIC,
565 "There was an IO error fetching the elastic document for upsert. Error: " + exc.getMessage());
571 * Populate aggregation entity document.
574 * @param result the result
575 * @param resultDescriptor the result descriptor
576 * @throws JsonProcessingException the json processing exception
577 * @throws IOException Signals that an I/O exception has occurred.
579 protected void populateAggregationEntityDocument(AggregationEntity doc, String result,
580 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
581 doc.setEntityType(resultDescriptor.getEntityName());
582 JsonNode entityNode = mapper.readTree(result);
583 Map<String, Object> map = mapper.convertValue(entityNode, Map.class);
584 doc.copyAttributeKeyValuePair(map);
588 * Process entity type self links.
590 * @param operationResult the operation result
592 private void processEntityTypeSelfLinks(OperationResult operationResult) {
594 if (operationResult == null) {
598 final String jsonResult = operationResult.getResult();
600 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
603 JsonNode rootNode = mapper.readTree(jsonResult);
605 JsonNode resultData = rootNode.get("result-data");
607 if (resultData.isArray()) {
608 ArrayNode resultDataArrayNode = (ArrayNode) resultData;
610 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
612 while (elementIterator.hasNext()) {
613 JsonNode element = elementIterator.next();
615 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
616 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
618 if (resourceType != null && resourceLink != null) {
620 OxmEntityDescriptor descriptor = oxmEntityLookup.getEntityDescriptors().get(resourceType);
622 if (descriptor == null) {
623 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
624 // go to next element in iterator
628 selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
633 } catch (IOException exc) {
635 "Could not deserialize JSON (representing operation result) as node tree. " +
636 "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
637 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
646 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
649 public OperationState doSync() {
650 this.syncDurationInMs = -1;
651 syncStartedTimeStampInMs = System.currentTimeMillis();
652 String txnID = NodeUtils.getRandomTxnId();
653 MdcContext.initialize(txnID, "AggregationSynchronizer", "", "Sync", "");
655 return collectAllTheWork();
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);
680 public String getEntityType() {
684 public void setEntityType(String entityType) {
685 this.entityType = entityType;
691 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
694 public void shutdown() {
695 this.shutdownExecutors();
699 protected boolean isSyncDone() {
701 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
703 if (LOG.isDebugEnabled()) {
704 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + ", isSyncDone(), totalWorkOnHand = "
705 + totalWorkOnHand + " all work enumerated = " + allWorkEnumerated);
708 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
712 this.syncInProgress = false;
720 * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
723 public void clearCache() {
725 if (syncInProgress) {
726 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
727 "Autosuggestion Entity Summarizer in progress, request to clear cache ignored");
732 this.resetCounters();
733 if (entityCounters != null) {
734 entityCounters.clear();
737 allWorkEnumerated = false;