2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.model.cache;
23 import fj.data.Either;
25 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
26 import org.apache.commons.lang3.tuple.ImmutablePair;
27 import org.openecomp.sdc.be.config.BeEcompErrorManager;
28 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
29 import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig;
30 import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheInfo;
31 import org.openecomp.sdc.be.config.ConfigurationManager;
32 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
33 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
34 import org.openecomp.sdc.be.model.DataTypeDefinition;
35 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
36 import org.openecomp.sdc.be.resources.data.DataTypeData;
37 import org.openecomp.sdc.common.log.wrappers.Logger;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.context.ApplicationEvent;
40 import org.springframework.context.ApplicationEventPublisher;
41 import org.springframework.stereotype.Component;
43 import javax.annotation.PostConstruct;
44 import javax.annotation.PreDestroy;
45 import javax.annotation.Resource;
46 import java.util.HashMap;
47 import java.util.List;
49 import java.util.Map.Entry;
51 import java.util.concurrent.Executors;
52 import java.util.concurrent.ScheduledExecutorService;
53 import java.util.concurrent.ScheduledFuture;
54 import java.util.concurrent.TimeUnit;
55 import java.util.concurrent.locks.Lock;
56 import java.util.concurrent.locks.ReentrantReadWriteLock;
57 import java.util.stream.Collectors;
59 @Component("application-datatype-cache")
60 public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefinition>, Runnable {
62 private static final String APPLICATION_DATA_TYPES_CACHE = "ApplicationDataTypesCache";
63 private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
64 private final Lock r = rwl.readLock();
65 private final Lock w = rwl.writeLock();
67 private Map<String, DataTypeDefinition> data = new HashMap<>();
69 private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1,
70 new BasicThreadFactory.Builder().namingPattern("ApplicationDataTypeCacheThread-%d").build());
71 ScheduledFuture<?> scheduledFuture = null;
73 private static final Logger log = Logger.getLogger(ApplicationDataTypeCache.class.getName());
75 private int firstRunDelayInSec = 30;
76 private int pollingIntervalInSec = 60;
79 private PropertyOperation propertyOperation;
82 private ApplicationEventPublisher applicationEventPublisher;
87 ApplicationL1CacheConfig applicationL1CacheConfig = ConfigurationManager.getConfigurationManager()
88 .getConfiguration().getApplicationL1Cache();
89 if (applicationL1CacheConfig != null) {
90 if (applicationL1CacheConfig.getDatatypes() != null) {
91 ApplicationL1CacheInfo datatypesInfo = applicationL1CacheConfig.getDatatypes();
92 if (datatypesInfo.getEnabled()) {
93 Integer intervalInSec = datatypesInfo.getPollIntervalInSec();
94 if (intervalInSec != null) {
95 pollingIntervalInSec = intervalInSec;
97 Integer firstRunDelay = datatypesInfo.getFirstRunDelay();
98 if (firstRunDelay != null) {
99 firstRunDelayInSec = firstRunDelay;
101 log.trace("ApplicationDataTypesCache polling interval is {} seconds.", pollingIntervalInSec);
102 if (scheduledPollingService != null) {
103 log.debug("Start ApplicationDataTypeCache polling task. polling interval {} seconds",
104 pollingIntervalInSec);
105 scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, firstRunDelayInSec,
106 pollingIntervalInSec, TimeUnit.SECONDS);
111 BeEcompErrorManager.getInstance().logInternalFlowError(APPLICATION_DATA_TYPES_CACHE, "Cache is disabled",
115 BeEcompErrorManager.getInstance().logInternalFlowError(APPLICATION_DATA_TYPES_CACHE, "Cache is disabled",
124 if (scheduledFuture != null) {
125 boolean result = scheduledFuture.cancel(true);
126 log.debug("Stop polling task. result = {}", result);
128 scheduledFuture = null;
133 private void shutdownExecutor() {
134 if (scheduledPollingService == null)
137 scheduledPollingService.shutdown(); // Disable new tasks from being
140 // Wait a while for existing tasks to terminate
141 if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
142 scheduledPollingService.shutdownNow(); // Cancel currently
144 // Wait a while for tasks to respond to being cancelled
145 if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
146 log.debug("Pool did not terminate");
148 } catch (InterruptedException ie) {
149 // (Re-)Cancel if current thread also interrupted
150 scheduledPollingService.shutdownNow();
151 // Preserve interrupt status
152 Thread.currentThread().interrupt();
156 private Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> getAllDataTypesFromGraph() {
158 return propertyOperation
164 public Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> getAll() {
169 if (data == null || data.isEmpty()) {
170 return getAllDataTypesFromGraph();
173 return Either.left(data);
181 public Either<DataTypeDefinition, JanusGraphOperationStatus> get(String uniqueId) {
186 if (data == null || data.isEmpty()) {
187 return propertyOperation
188 .getDataTypeByUid(uniqueId);
190 DataTypeDefinition dataTypeDefinition = data.values().stream()
191 .filter(p -> p.getUniqueId().equals(uniqueId)).findFirst().orElse(null);
192 if (dataTypeDefinition == null) {
193 return propertyOperation
194 .getDataTypeByUid(uniqueId);
196 return Either.left(dataTypeDefinition);
206 log.trace("run() method. polling db to fetch data types");
210 Long start = System.currentTimeMillis();
211 log.trace("Start fetching all data types from db");
212 Either<List<DataTypeData>, JanusGraphOperationStatus> allDataTypeNodes = propertyOperation.getAllDataTypeNodes();
213 Long end = System.currentTimeMillis();
214 log.trace("Finish fetching all data types from db. Took {} Milliseconds", (end - start));
215 if (allDataTypeNodes.isRight()) {
216 JanusGraphOperationStatus status = allDataTypeNodes.right().value();
217 if (status != JanusGraphOperationStatus.OK) {
218 log.debug("ApplicationDataTypesCache - Failed to fetch all data types nodes");
219 BeEcompErrorManager.getInstance().logInternalConnectionError("FetchDataTypes",
220 "Failed to fetch data types from graph(cache)", ErrorSeverity.INFO);
224 List<DataTypeData> list = allDataTypeNodes.left().value();
227 Map<String, ImmutablePair<Long, Long>> dataTypeNameToModificationTime = list.stream()
228 .collect(Collectors.toMap(p -> p.getDataTypeDataDefinition().getName(),
229 p -> new ImmutablePair<>(p.getDataTypeDataDefinition().getCreationTime(),
230 p.getDataTypeDataDefinition().getModificationTime())));
232 Map<String, ImmutablePair<Long, Long>> currentDataTypeToModificationTime = new HashMap<>();
236 currentDataTypeToModificationTime = data.values().stream().collect(Collectors.toMap(
237 DataTypeDataDefinition::getName,
238 p -> new ImmutablePair<>(p.getCreationTime(), p.getModificationTime())));
245 boolean isChanged = compareDataTypes(dataTypeNameToModificationTime,
246 currentDataTypeToModificationTime);
254 } catch (Exception e) {
255 log.debug("unexpected error occured", e);
257 BeEcompErrorManager.getInstance().logInternalUnexpectedError(APPLICATION_DATA_TYPES_CACHE,
258 "Failed to run refresh data types job", ErrorSeverity.INFO);
261 propertyOperation.getJanusGraphGenericDao().commit();
262 } catch (Exception e) {
263 log.trace("Failed to commit ApplicationDataTypeCache", e);
269 private boolean compareDataTypes(Map<String, ImmutablePair<Long, Long>> dataTypeNameToModificationTime,
270 Map<String, ImmutablePair<Long, Long>> currentDataTypeToModificationTime) {
271 if (dataTypeNameToModificationTime.size() != currentDataTypeToModificationTime.size()) {
275 Set<String> currentkeySet = currentDataTypeToModificationTime.keySet();
276 Set<String> keySet = dataTypeNameToModificationTime.keySet();
278 if (currentkeySet.containsAll(keySet)) {
280 for (Entry<String, ImmutablePair<Long, Long>> entry : dataTypeNameToModificationTime.entrySet()) {
281 String dataTypeName = entry.getKey();
282 ImmutablePair<Long, Long> creationAndModificationTimes = entry.getValue();
283 long creationTime = creationAndModificationTimes.getLeft() == null ? 0
284 : creationAndModificationTimes.getLeft().longValue();
285 long modificationTime = creationAndModificationTimes.getRight() == null ? 0
286 : creationAndModificationTimes.getRight().longValue();
288 ImmutablePair<Long, Long> currentEntry = currentDataTypeToModificationTime.get(dataTypeName);
289 long currentCreationTime = currentEntry.getLeft() == null ? 0 : currentEntry.getLeft().longValue();
290 long currentModificationTime = currentEntry.getRight() == null ? 0
291 : currentEntry.getRight().longValue();
293 if (creationTime > currentCreationTime || modificationTime > currentModificationTime) {
294 log.debug("Datatype {} was updated. Creation Time {} vs {}. Modification Time {} vs {}",
295 dataTypeName, currentCreationTime, creationTime, currentModificationTime,
309 private void replaceAllData() {
311 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = propertyOperation
314 if (allDataTypes.isRight()) {
315 JanusGraphOperationStatus status = allDataTypes.right().value();
316 log.debug("Failed to fetch all data types from db. Status is {}", status);
322 data = allDataTypes.left().value();
323 // send notification on data types change
324 onDataChangeEventEmit(data);
326 BeEcompErrorManager.getInstance().logInternalFlowError("ReplaceDataTypesCache",
327 "Succeed to replace the data types cache", ErrorSeverity.INFO);
337 private void onDataChangeEventEmit(Map<String, DataTypeDefinition> newData) {
338 log.trace("Cache data has changed, sending event to all listening for this change.");
339 DataTypesCacheChangedEvent dataTypesCacheChangedEvent = new DataTypesCacheChangedEvent(this, newData);
340 applicationEventPublisher.publishEvent(dataTypesCacheChangedEvent);
344 * Custom event to notify all interested in cached data changes
346 public static class DataTypesCacheChangedEvent extends ApplicationEvent {
348 private Map<String, DataTypeDefinition> newData;
350 public DataTypesCacheChangedEvent(Object source, Map<String, DataTypeDefinition> newData) {
352 this.newData = newData;