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.sql.Timestamp;
27 import java.text.SimpleDateFormat;
28 import java.util.Collection;
29 import java.util.EnumSet;
31 import java.util.Map.Entry;
33 import java.util.concurrent.ConcurrentHashMap;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.function.Supplier;
37 import javax.json.Json;
38 import javax.ws.rs.core.MediaType;
40 import org.onap.aai.cl.api.Logger;
41 import org.onap.aai.cl.eelf.LoggerFactory;
42 import org.onap.aai.cl.mdc.MdcContext;
43 import org.onap.aai.restclient.client.OperationResult;
44 import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
45 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
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.config.ElasticSearchSchemaConfig;
51 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
52 import org.onap.aai.sparky.sync.enumeration.OperationState;
53 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
54 import org.onap.aai.sparky.util.NodeUtils;
57 import com.fasterxml.jackson.databind.JsonNode;
58 import com.fasterxml.jackson.databind.node.ArrayNode;
61 * The Class HistoricalEntitySummarizer.
63 public class HistoricalEntitySummarizer extends AbstractEntitySynchronizer
64 implements IndexSynchronizer {
66 private static final Logger LOG = LoggerFactory.getInstance().getLogger(HistoricalEntitySummarizer.class);
67 private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ";
69 private boolean allWorkEnumerated;
70 private ConcurrentHashMap<String, AtomicInteger> entityCounters;
71 private boolean syncInProgress;
72 private Map<String, String> contextMap;
73 private ElasticSearchSchemaConfig schemaConfig;
74 private SearchableEntityLookup searchableEntityLookup;
77 * Instantiates a new historical entity summarizer.
79 * @throws Exception the exception
81 public HistoricalEntitySummarizer(ElasticSearchSchemaConfig schemaConfig, int internalSyncWorkers,
82 int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
83 NetworkStatisticsConfig esStatConfig, SearchableEntityLookup searchableEntityLookup)
85 super(LOG, "HES", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(), aaiStatConfig, esStatConfig);
87 this.schemaConfig = schemaConfig;
88 this.allWorkEnumerated = false;
89 this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>();
90 this.synchronizerName = "Historical Entity Summarizer";
91 this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS);
92 this.syncInProgress = false;
93 this.contextMap = MDC.getCopyOfContextMap();
94 this.syncDurationInMs = -1;
95 this.searchableEntityLookup = searchableEntityLookup;
99 * Collect all the work.
101 * @return the operation state
103 private OperationState collectAllTheWork() {
105 Map<String, SearchableOxmEntityDescriptor> descriptorMap =
106 searchableEntityLookup.getSearchableEntityDescriptors();
108 if (descriptorMap.isEmpty()) {
109 LOG.error(AaiUiMsgs.OXM_FAILED_RETRIEVAL, "historical entities");
111 return OperationState.ERROR;
114 Collection<String> entityTypes = descriptorMap.keySet();
116 AtomicInteger asyncWoH = new AtomicInteger(0);
118 asyncWoH.set(entityTypes.size());
121 for (String entityType : entityTypes) {
123 supplyAsync(new Supplier<Void>() {
127 MDC.setContextMap(contextMap);
129 OperationResult typeLinksResult =
130 aaiAdapter.getSelfLinksByEntityType(entityType);
131 updateActiveInventoryCounters(HttpMethod.GET, entityType, typeLinksResult);
132 processEntityTypeSelfLinks(entityType, typeLinksResult);
133 } catch (Exception exc) {
134 LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, exc.getMessage());
141 }, aaiExecutor).whenComplete((result, error) -> {
143 asyncWoH.decrementAndGet();
146 LOG.error(AaiUiMsgs.HISTORICAL_COLLECT_ERROR, error.getMessage());
154 while (asyncWoH.get() > 0) {
156 if (LOG.isDebugEnabled()) {
157 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + " summarizer waiting for all the links to be processed.");
163 esWorkOnHand.set(entityCounters.size());
165 // start doing the real work
166 allWorkEnumerated = true;
168 insertEntityTypeCounters();
170 if (LOG.isDebugEnabled()) {
172 StringBuilder sb = new StringBuilder(128);
174 sb.append("\n\nHistorical Entity Counters:");
176 for (Entry<String, AtomicInteger> entry : entityCounters.entrySet()) {
177 sb.append("\n").append(entry.getKey()).append(" = ").append(entry.getValue().get());
180 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, sb.toString());
184 } catch (Exception exc) {
185 LOG.error(AaiUiMsgs.HISTORICAL_COLLECT_ERROR, exc.getMessage());
189 allWorkEnumerated = true;
191 return OperationState.ERROR;
194 return OperationState.OK;
199 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
202 public OperationState doSync() {
203 this.syncDurationInMs = -1;
204 String txnID = NodeUtils.getRandomTxnId();
205 MdcContext.initialize(txnID, "HistoricalEntitySynchronizer", "", "Sync", "");
207 if (syncInProgress) {
208 LOG.info(AaiUiMsgs.HISTORICAL_SYNC_PENDING);
209 return OperationState.PENDING;
214 syncInProgress = true;
215 this.syncStartedTimeStampInMs = System.currentTimeMillis();
216 allWorkEnumerated = false;
218 return collectAllTheWork();
222 * Process entity type self links.
224 * @param entityType the entity type
225 * @param operationResult the operation result
227 private void processEntityTypeSelfLinks(String entityType, OperationResult operationResult) {
229 JsonNode rootNode = null;
231 final String jsonResult = operationResult.getResult();
233 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
236 rootNode = mapper.readTree(jsonResult);
237 } catch (IOException exc) {
238 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, exc.getMessage());
242 JsonNode resultData = rootNode.get("result-data");
243 ArrayNode resultDataArrayNode = null;
245 if (resultData != null && resultData.isArray()) {
246 resultDataArrayNode = (ArrayNode) resultData;
247 entityCounters.put(entityType, new AtomicInteger(resultDataArrayNode.size()));
254 * Insert entity type counters.
256 private void insertEntityTypeCounters() {
258 if (esWorkOnHand.get() <= 0) {
262 SimpleDateFormat dateFormat = new SimpleDateFormat(INSERTION_DATE_TIME_FORMAT);
263 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
264 String currentFormattedTimeStamp = dateFormat.format(timestamp);
266 Set<Entry<String, AtomicInteger>> entityCounterEntries = entityCounters.entrySet();
268 for (Entry<String, AtomicInteger> entityCounterEntry : entityCounterEntries) {
270 supplyAsync(new Supplier<Void>() {
274 MDC.setContextMap(contextMap);
275 String jsonString = Json.createObjectBuilder().add(
276 "count", entityCounterEntry.getValue().get())
277 .add("entityType", entityCounterEntry.getKey())
278 .add("timestamp", currentFormattedTimeStamp).build().toString();
282 link = elasticSearchAdapter.buildElasticSearchPostUrl(indexName);
283 OperationResult or = elasticSearchAdapter.doPost(link, jsonString, MediaType.APPLICATION_JSON_TYPE);
284 updateElasticSearchCounters(HttpMethod.POST, entityCounterEntry.getKey(), or);
285 } catch (Exception exc) {
286 LOG.error(AaiUiMsgs.ES_STORE_FAILURE, exc.getMessage() );
292 }, esExecutor).whenComplete((result, error) -> {
294 esWorkOnHand.decrementAndGet();
300 while (esWorkOnHand.get() > 0) {
304 } catch (InterruptedException exc) {
305 LOG.error(AaiUiMsgs.INTERRUPTED, "historical Entities", exc.getMessage());
306 Thread.currentThread().interrupt();
313 public SynchronizerState getState() {
316 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
319 return SynchronizerState.IDLE;
324 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
327 public String getStatReport(boolean showFinalReport) {
328 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
329 return this.getStatReport(syncDurationInMs, showFinalReport);
333 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
336 public void shutdown() {
337 this.shutdownExecutors();
341 protected boolean isSyncDone() {
343 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
345 if (LOG.isDebugEnabled()) {
346 LOG.debug(AaiUiMsgs.DEBUG_GENERIC,indexName + ", isSyncDone(), totalWorkOnHand = " + totalWorkOnHand
347 + " all work enumerated = " + allWorkEnumerated);
350 if (totalWorkOnHand > 0 || !allWorkEnumerated) {
354 this.syncInProgress = false;
360 * @see org.openecomp.sparky.synchronizer.AbstractEntitySynchronizer#clearCache()
363 public void clearCache() {
365 if (syncInProgress) {
366 LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Historical Entity Summarizer in progress, request to clear cache ignored");
371 this.resetCounters();
372 if (entityCounters != null) {
373 entityCounters.clear();
376 allWorkEnumerated = false;