Alachisoft.NCache.MetricServer.SessionManager Maven / Gradle / Ivy
The newest version!
package Alachisoft.NCache.MetricServer;
import Alachisoft.NCache.Common.Logger.*;
import Alachisoft.NCache.Common.Monitoring.*;
import Alachisoft.NCache.Common.Monitoring.MetricsServer.BridgeCacheMetaData;
import Alachisoft.NCache.Common.Monitoring.MetricsServer.BridgeMetaData;
import Alachisoft.NCache.Common.Monitoring.MetricsServer.CacheMetaData;
import Alachisoft.NCache.Common.ServiceConfiguration;
import Alachisoft.NCache.Common.Util.*;
import Alachisoft.NCache.DataModel.Bridge;
import Alachisoft.NCache.DataModel.BridgeCache;
import Alachisoft.NCache.DataModel.CacheConfig;
import Alachisoft.NCache.DataModel.Client;
import Alachisoft.NCache.MetricsAgents.JMX.JMXAgent;
import Alachisoft.NCache.MetricsAgents.MetricsAgentManager;
import Alachisoft.NCache.Sessions.MetricsSession;
import Alachisoft.NCache.Sessions.MetricsSessions.*;
import Util.ExecutionServiceConfiguration;
import com.alachisoft.ncache.common.monitoring.ClientMetaData;
import com.alachisoft.ncache.common.monitoring.CounterDataCollection;
import com.alachisoft.ncache.common.monitoring.CounterMetadataCollection;
import com.alachisoft.ncache.common.monitoring.PublishCountersDataResult;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SessionManager implements AutoCloseable {
private final String currentDatabaseVersion = "1.0.0";
private ILogger logger;
private Thread metricsPublisher;
private boolean isPersistenceEnabled = true;
private static boolean isLoaded;
private final int persistenceInterval = ServiceConfiguration.getMetricsMonitorPublishingInterval().getSeconds() * 1000; // milliseconds
private final Object clientSessionLock = new Object();
private MetricsAgentManager metricsAgentManager;
private final SessionIdManager sessionIdManager = new SessionIdManager();
private final Map index = new HashMap<>();
public SessionManager(ILogger logger) {
isLoaded = false;
this.logger = logger;
this.metricsAgentManager = new MetricsAgentManager();
initialize();
}
public void initialize() {
// if (ServiceConfiguration.EnablePrometheusMonitoring) {
// isPersistenceEnabled = true;
// PrometheusAgent prometheusAgent = new PrometheusAgent();
// prometheusAgent.initialize(logger);
// prometheusAgent.start();
// metricsAgentManager.addMetricsAgent(prometheusAgent);
// }
if (true) {
isPersistenceEnabled = true;
JMXAgent jmxAgent = new JMXAgent(ExecutionServiceConfiguration.getIsJMXEnabled());
jmxAgent.initialize(logger);
jmxAgent.start();
metricsAgentManager.addMetricsAgent(jmxAgent);
}
if (isPersistenceEnabled) {
if (metricsPublisher == null) {
metricsPublisher = new Thread(this::doBackgroundTasks);
metricsPublisher.setDaemon(true);
metricsPublisher.setName("MetricsPublisher");
metricsPublisher.start();
}
}
}
public ClientSession createClientSession(String sessionId, String version, Client clientMeta) {
ClientSession metricsSession = null;
synchronized (clientSessionLock) {
metricsSession = new ClientSession(sessionId, clientMeta);
metricsSession.setVersion(version);
metricsSession.initialize((JLogger) logger, metricsAgentManager);
}
return metricsSession;
}
public MetricsSession getOrCreateClientSession(String sessionId, String version, Client clientMeta) {
synchronized (index) {
if (!index.containsKey(sessionId)) {
index.put(sessionId, createClientSession(sessionId, version, clientMeta));
}
}
return index.get(sessionId);
}
public MetricsSession createBridgeSession(String sessionId, String version, Bridge bridgeMetadata) {
String session = sessionId;
synchronized (index) {
MetricsSession existingSession = index.get(session);
if (existingSession != null) {
existingSession.dispose();
index.remove(session);
}
BridgeSession metricsSession = new BridgeSession(sessionId, bridgeMetadata);
metricsSession.initialize((JLogger) logger, metricsAgentManager);
index.put(session, metricsSession);
}
return index.get(session);
}
public MetricsSession getOrCreateBridgedCacheSession(String sessionId, String version, BridgeCache bridgedCacheMetadata) {
String session = sessionId;
synchronized (index) {
if (!index.containsKey(session)) {
BridgedCacheSession metricsSession = new BridgedCacheSession(sessionId, bridgedCacheMetadata);
metricsSession.setVersion(version);
metricsSession.initialize((JLogger) logger, metricsAgentManager);
index.put(session, metricsSession);
}
return index.get(session);
}
}
public MetricsSession getOrCreateCacheSession(String sessionId, CacheConfig cacheMetadata, String version) {
String session = sessionId;
synchronized (index) {
if (!index.containsKey(session)) {
CacheSession metricsSession = new CacheSession(sessionId, cacheMetadata, version);
metricsSession.initialize((JLogger) logger, metricsAgentManager);
index.put(session, metricsSession);
}
return index.get(session);
}
}
public boolean isWriteActive(String sessionId) {
synchronized (index) {
if (index.containsKey(sessionId)) {
return index.get(sessionId).isWriteActive();
}
return false;
}
}
public boolean isReadActive(String sessionId) {
synchronized (index) {
if (index.containsKey(sessionId)) {
return index.get(sessionId).isReadActive();
}
return false;
}
}
public boolean isExpired(String sessionId) {
synchronized (index) {
if (index.containsKey(sessionId)) {
return index.get(sessionId).isExpired();
}
return true;
}
}
public Date lastUpdateTime(String sessionId) {
synchronized (index) {
if (index.containsKey(sessionId)) {
return index.get(sessionId).getLastWriteTime();
}
return null;
}
}
public void expireInactiveSessions(List metricsSessions) {
synchronized (index) {
try {
Iterator iterator = metricsSessions.iterator();
while (iterator.hasNext()) {
String sessionId = iterator.next();
MetricsSession session = index.get(sessionId);
if (session != null) {
session.dispose();
index.remove(sessionId);
}
}
} catch (Exception e) {
logger.Error("MetricServer SM", "Unable to expire session\n" + e.toString());
}
}
}
private void removeClientSession() {
// Implementation for removing client session
}
private void removeBridgeSession() {
// Implementation for removing bridge session
}
private void removeCacheSession() {
// Implementation for removing cache session
}
public PublishCountersDataResult publishCountersData(String sessionId, CounterDataCollection data) {
String sessionIdCopy = sessionIdManager.getSessionId(sessionId, data);
MetricsSession session = getSession(sessionIdCopy);
if (session == null)
return PublishCountersDataResult.CountersSessionExpired;
return publishCountersData(session, data);
}
public void publishCacheMetadata(String sessionId, String version, CacheMetaData cacheMeta) {
CacheConfig metadata = CacheConfig.fromCacheMetaData(cacheMeta);
String session = sessionIdManager.getSessionId(sessionId, cacheMeta);
CacheSession ncacheSession = (CacheSession) getOrCreateCacheSession(session, metadata, version);
if (ncacheSession instanceof CacheSession) {
((CacheSession) ncacheSession).setVersion(version);
}
}
public void publishClientMetadata(String sessionId, String version, ClientMetaData clientMeta) {
Client metadata = Client.fromClientMetaData(clientMeta);
metadata.setSessionId(sessionId);
String sessionIdCopy = sessionIdManager.getSessionId(sessionId, clientMeta);
ClientSession clientSession = (ClientSession) getOrCreateClientSession(sessionIdCopy, version, metadata);
if (clientSession instanceof ClientSession) {
((ClientSession) clientSession).setVersion(version);
}
}
public void publishBridgeMetadata(String sessionId, String version, BridgeMetaData bridgeMeta) {
Bridge metadata = Bridge.fromBridgeMetaData(bridgeMeta);
String session = sessionIdManager.getSessionId(sessionId, bridgeMeta);
BridgeSession bridgeSession = (BridgeSession) createBridgeSession(session, version, metadata);
if (bridgeSession instanceof BridgeSession) {
((BridgeSession) bridgeSession).setVersion(version);
}
}
public void publishBridgedCacheMetadata(String sessionId, String version, BridgeCacheMetaData clientMeta) {
BridgeCache metadata = BridgeCache.fromBridgedCacheMetaData(clientMeta);
String session = sessionIdManager.getSessionId(sessionId, clientMeta);
BridgedCacheSession clientSession = (BridgedCacheSession) getOrCreateBridgedCacheSession(session, version, metadata);
if (clientSession instanceof BridgedCacheSession) {
((BridgedCacheSession) clientSession).setVersion(version);
}
}
public void publishCountersMetadata(String sessionId, CounterMetadataCollection counterMeta) {
String sessionIdCopy = sessionIdManager.getSessionId(sessionId, counterMeta);
MetricsSession metricSession = getSession(sessionIdCopy);
if (metricSession != null) {
metricSession.addCountersMetadata(counterMeta);
metricSession.createCounters();
}
}
private PublishCountersDataResult publishCountersData(MetricsSession session, CounterDataCollection counterData) {
if (!session.isMetadataPersisted())
return PublishCountersDataResult.CountersMetaDataNotPersisted;
session.addCountersData(session.getSessionId(), counterData);
return PublishCountersDataResult.DataPersistedSuccessfully;
}
// Background Task
public void doBackgroundTasks() {
try {
List sessionsToExpire = new ArrayList<>();
while (isPersistenceEnabled) {
try {
Thread.sleep(persistenceInterval);
String key = "";
MetricsSession session = null;
List sessionKeys = new ArrayList<>();
synchronized (index) {
if (index.isEmpty())
continue;
for (String item : index.keySet()) {
sessionKeys.add(item);
}
}
Iterator iterator = sessionKeys.iterator();
while (iterator.hasNext()) {
try {
boolean sessionExists = false;
String sessionKey = iterator.next();
synchronized (index) {
sessionExists = index.containsKey(sessionKey);
if (sessionExists) {
session = index.get(sessionKey);
}
}
if (sessionExists) {
session.persist();
if (session.isExpired()) {
sessionsToExpire.add(sessionKey);
}
}
} catch (Exception e) {
logger.Error("SM MetricServer", "Unable to persist Session: " + key + "\n" + e.toString());
}
}
expireInactiveSessions(sessionsToExpire);
sessionsToExpire.clear();
} catch (InterruptedException e) {
break;
} catch (Exception e) {
logger.Error("SM MetricServer Persistor", e.toString());
}
}
} catch (Exception e) {
logger.Error("SM MetricServer Persistor", "Persistor Stopped due to\n" + e.toString());
}
}
@Override
public void close() {
try {
isPersistenceEnabled = false;
if (metricsPublisher != null && metricsPublisher.isAlive()) {
// Assuming that _metricsPublisher is a Thread object
metricsPublisher.interrupt();
}
metricsAgentManager.close();
} catch (Exception e) {
// Handle exception as needed
}
}
public MetricsSession getSession(String sessionId) {
MetricsSession metricSession = null;
String session = String.valueOf(sessionId);
synchronized (index) {
metricSession = index.get(session);
}
return metricSession;
}
}