use of org.apache.geode.security.GemFireSecurityException in project geode by apache.
the class ClientCQImpl method executeCqOnRedundantsAndPrimary.
/**
* This executes the CQ first on the redundant server and then on the primary server. This is
* required to keep the redundancy behavior in accordance with the HAQueue expectation (wherein
* the events are delivered only from the primary).
*
* @param executeWithInitialResults boolean
* @return Object SelectResults in case of executeWithInitialResults
*/
private Object executeCqOnRedundantsAndPrimary(boolean executeWithInitialResults) throws CqClosedException, RegionNotFoundException, CqException {
Object initialResults = null;
synchronized (this.cqState) {
if (this.isClosed()) {
throw new CqClosedException(LocalizedStrings.CqQueryImpl_CQ_IS_CLOSED_CQNAME_0.toLocalizedString(this.cqName));
}
if (this.isRunning()) {
throw new IllegalStateException(LocalizedStrings.CqQueryImpl_CQ_IS_IN_RUNNING_STATE_CQNAME_0.toLocalizedString(this.cqName));
}
if (logger.isDebugEnabled()) {
logger.debug("Performing Execute {} request for CQ. CqName: {}", ((executeWithInitialResults) ? "WithInitialResult" : ""), this.cqName);
}
this.cqBaseRegion = (LocalRegion) cqService.getCache().getRegion(this.regionName);
// If not server send the request to server.
if (!cqService.isServer()) {
// pool that initializes the CQ. Else its set using the Region proxy.
if (this.cqProxy == null) {
initConnectionProxy();
}
boolean success = false;
try {
if (this.proxyCache != null) {
if (this.proxyCache.isClosed()) {
throw new CacheClosedException("Cache is closed for this user.");
}
UserAttributes.userAttributes.set(this.proxyCache.getUserAttributes());
}
if (executeWithInitialResults) {
initialResults = cqProxy.createWithIR(this);
if (initialResults == null) {
String errMsg = "Failed to execute the CQ. CqName: " + this.cqName + ", Query String is: " + this.queryString;
throw new CqException(errMsg);
}
} else {
cqProxy.create(this);
}
success = true;
} catch (Exception ex) {
// Check for system shutdown.
if (this.shutdownInProgress()) {
throw new CqException("System shutdown in progress.");
}
if (ex.getCause() instanceof GemFireSecurityException) {
if (securityLogWriter.warningEnabled()) {
securityLogWriter.warning(LocalizedStrings.CqQueryImpl_EXCEPTION_WHILE_EXECUTING_CQ_EXCEPTION_0, ex, null);
}
throw new CqException(ex.getCause().getMessage(), ex.getCause());
} else if (ex instanceof CqException) {
throw (CqException) ex;
} else {
String errMsg = LocalizedStrings.CqQueryImpl_FAILED_TO_EXECUTE_THE_CQ_CQNAME_0_QUERY_STRING_IS_1_ERROR_FROM_LAST_SERVER_2.toLocalizedString(this.cqName, this.queryString, ex.getLocalizedMessage());
if (logger.isDebugEnabled()) {
logger.debug(errMsg, ex);
}
throw new CqException(errMsg, ex);
}
} finally {
if (!success && !this.shutdownInProgress()) {
try {
cqProxy.close(this);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Exception cleaning up failed cq", e);
}
UserAttributes.userAttributes.set(null);
}
}
UserAttributes.userAttributes.set(null);
}
}
this.cqState.setState(CqStateImpl.RUNNING);
}
// If client side, alert listeners that a cqs have been connected
if (!cqService.isServer()) {
connected = true;
CqListener[] cqListeners = getCqAttributes().getCqListeners();
for (int lCnt = 0; lCnt < cqListeners.length; lCnt++) {
if (cqListeners[lCnt] != null) {
if (cqListeners[lCnt] instanceof CqStatusListener) {
CqStatusListener listener = (CqStatusListener) cqListeners[lCnt];
listener.onCqConnected();
}
}
}
}
// Update CQ-base region for book keeping.
this.cqService.stats().incCqsActive();
this.cqService.stats().decCqsStopped();
return initialResults;
}
use of org.apache.geode.security.GemFireSecurityException in project geode by apache.
the class QueueManagerImpl method initializeConnections.
private void initializeConnections() {
final boolean isDebugEnabled = logger.isDebugEnabled();
if (isDebugEnabled) {
logger.debug("SubscriptionManager - intitializing connections");
}
int queuesNeeded = redundancyLevel == -1 ? -1 : redundancyLevel + 1;
Set excludedServers = new HashSet(blackList.getBadServers());
List servers = findQueueServers(excludedServers, queuesNeeded, true, false, null);
if (servers == null || servers.isEmpty()) {
logger.warn(LocalizedStrings.QueueManagerImpl_COULD_NOT_CREATE_A_QUEUE_NO_QUEUE_SERVERS_AVAILABLE);
scheduleRedundancySatisfierIfNeeded(redundancyRetryInterval);
synchronized (lock) {
queueConnections = queueConnections.setPrimaryDiscoveryFailed(null);
lock.notifyAll();
}
return;
}
if (isDebugEnabled) {
logger.debug("SubscriptionManager - discovered subscription servers {}", servers);
}
SortedMap /* <ServerQueueStatus,Connection> */
oldQueueServers = new TreeMap(QSIZE_COMPARATOR);
List nonRedundantServers = new ArrayList();
for (Iterator itr = servers.iterator(); itr.hasNext(); ) {
ServerLocation server = (ServerLocation) itr.next();
Connection connection = null;
try {
connection = factory.createClientToServerConnection(server, true);
} catch (GemFireSecurityException e) {
throw e;
} catch (GemFireConfigException e) {
throw e;
} catch (Exception e) {
if (isDebugEnabled) {
logger.debug("SubscriptionManager - Error connected to server: {}", server, e);
}
}
if (connection != null) {
ServerQueueStatus status = connection.getQueueStatus();
if (status.isRedundant() || status.isPrimary()) {
oldQueueServers.put(status, connection);
} else {
nonRedundantServers.add(connection);
}
}
}
// This ordering was determined from the old ConnectionProxyImpl code
//
// initialization order of the new redundant and primary server is
// old redundant w/ second largest queue
// old redundant w/ third largest queue
// ...
// old primary
// non redundants in no particular order
//
// The primary is then chosen as
// redundant with the largest queue
// primary if there are no redundants
// a non redundant
// if the redundant with the largest queue fails, then we go and
// make a new server a primary.
Connection newPrimary = null;
if (!oldQueueServers.isEmpty()) {
newPrimary = (Connection) oldQueueServers.remove(oldQueueServers.lastKey());
} else if (!nonRedundantServers.isEmpty()) {
newPrimary = (Connection) nonRedundantServers.remove(0);
}
nonRedundantServers.addAll(0, oldQueueServers.values());
for (Iterator itr = nonRedundantServers.iterator(); itr.hasNext(); ) {
Connection connection = (Connection) itr.next();
QueueConnectionImpl queueConnection = initializeQueueConnection(connection, false, null);
if (queueConnection != null) {
addToConnectionList(queueConnection, false);
}
}
QueueConnectionImpl primaryQueue = null;
if (newPrimary != null) {
primaryQueue = initializeQueueConnection(newPrimary, true, null);
if (primaryQueue == null) {
newPrimary.destroy();
} else {
if (!addToConnectionList(primaryQueue, true)) {
primaryQueue = null;
}
}
}
excludedServers.addAll(servers);
// above.
if (redundancyLevel != -1 && getCurrentRedundancy() < redundancyLevel) {
if (isDebugEnabled) {
logger.debug("SubscriptionManager - Some initial connections failed. Trying to create redundant queues");
}
recoverRedundancy(excludedServers, false);
}
if (redundancyLevel != -1 && primaryQueue == null) {
if (isDebugEnabled) {
logger.debug("SubscriptionManager - Intial primary creation failed. Trying to create a new primary");
}
while (primaryQueue == null) {
primaryQueue = createNewPrimary(excludedServers);
if (primaryQueue == null) {
// couldn't find a server to make primary
break;
}
if (!addToConnectionList(primaryQueue, true)) {
excludedServers.add(primaryQueue.getServer());
primaryQueue = null;
}
}
}
if (primaryQueue == null) {
if (isDebugEnabled) {
logger.debug("SubscriptionManager - Unable to create a new primary queue, using one of the redundant queues");
}
while (primaryQueue == null) {
primaryQueue = promoteBackupToPrimary(queueConnections.getBackups());
if (primaryQueue == null) {
// no backup servers available
break;
}
if (!addToConnectionList(primaryQueue, true)) {
synchronized (lock) {
// make sure we don't retry this same connection.
queueConnections = queueConnections.removeConnection(primaryQueue);
}
primaryQueue = null;
}
}
}
if (primaryQueue == null) {
logger.error(LocalizedMessage.create(LocalizedStrings.QueueManagerImpl_COULD_NOT_INITIALIZE_A_PRIMARY_QUEUE_ON_STARTUP_NO_QUEUE_SERVERS_AVAILABLE));
synchronized (lock) {
queueConnections = queueConnections.setPrimaryDiscoveryFailed(new NoSubscriptionServersAvailableException(LocalizedStrings.QueueManagerImpl_COULD_NOT_INITIALIZE_A_PRIMARY_QUEUE_ON_STARTUP_NO_QUEUE_SERVERS_AVAILABLE.toLocalizedString()));
lock.notifyAll();
}
cqsDisconnected();
} else {
cqsConnected();
}
if (getCurrentRedundancy() < redundancyLevel) {
logger.warn(LocalizedMessage.create(LocalizedStrings.QueueManagerImpl_UNABLE_TO_INITIALIZE_ENOUGH_REDUNDANT_QUEUES_ON_STARTUP_THE_REDUNDANCY_COUNT_IS_CURRENTLY_0, getCurrentRedundancy()));
}
}
use of org.apache.geode.security.GemFireSecurityException in project geode by apache.
the class QueueManagerImpl method createNewPrimary.
/**
* Create a new primary server from a non-redundant server.
*
* Add any failed servers to the excludedServers set.
*/
private QueueConnectionImpl createNewPrimary(Set excludedServers) {
QueueConnectionImpl primary = null;
while (primary == null && pool.getPoolOrCacheCancelInProgress() == null) {
List servers = findQueueServers(excludedServers, 1, false, printPrimaryNotFoundError, LocalizedStrings.QueueManagerImpl_COULD_NOT_FIND_SERVER_TO_CREATE_PRIMARY_CLIENT_QUEUE);
// printed above
printPrimaryNotFoundError = false;
if (servers == null || servers.isEmpty()) {
break;
}
Connection connection = null;
try {
connection = factory.createClientToServerConnection((ServerLocation) servers.get(0), true);
} catch (GemFireSecurityException e) {
throw e;
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("SubscriptionManagerImpl - error creating a connection to server {}", servers.get(0));
}
}
if (connection != null) {
primary = initializeQueueConnection(connection, true, queueConnections.getFailedUpdater());
}
excludedServers.addAll(servers);
}
if (primary != null && sentClientReady && primary.sendClientReady()) {
readyForEventsAfterFailover(primary);
}
return primary;
}
use of org.apache.geode.security.GemFireSecurityException in project geode by apache.
the class QueueManagerImpl method recoverRedundancy.
/**
* Make sure that we have enough backup servers.
*
* Add any servers we fail to connect to to the excluded servers list.
*/
protected boolean recoverRedundancy(Set excludedServers, boolean recoverInterest) {
if (pool.getPoolOrCacheCancelInProgress() != null) {
return true;
}
int additionalBackups;
while (pool.getPoolOrCacheCancelInProgress() == null && ((additionalBackups = redundancyLevel - getCurrentRedundancy()) > 0 || redundancyLevel == -1)) {
if (redundancyLevel != -1 && printRecoveringRedundant) {
logger.info(LocalizedMessage.create(LocalizedStrings.QueueManagerImpl_SUBSCRIPTION_MANAGER_REDUNDANCY_SATISFIER_REDUNDANT_ENDPOINT_HAS_BEEN_LOST_ATTEMPTIMG_TO_RECOVER));
printRecoveringRedundant = false;
}
List servers = findQueueServers(excludedServers, redundancyLevel == -1 ? -1 : additionalBackups, false, (redundancyLevel == -1 ? false : printRedundancyNotSatisfiedError), LocalizedStrings.QueueManagerImpl_COULD_NOT_FIND_SERVER_TO_CREATE_REDUNDANT_CLIENT_QUEUE);
if (servers == null || servers.isEmpty()) {
if (redundancyLevel != -1) {
if (printRedundancyNotSatisfiedError) {
logger.info(LocalizedMessage.create(LocalizedStrings.QueueManagerImpl_REDUNDANCY_LEVEL_0_IS_NOT_SATISFIED_BUT_THERE_ARE_NO_MORE_SERVERS_AVAILABLE_REDUNDANCY_IS_CURRENTLY_1, new Object[] { redundancyLevel, getCurrentRedundancy() }));
}
}
// printed above
printRedundancyNotSatisfiedError = false;
return false;
}
excludedServers.addAll(servers);
final boolean isDebugEnabled = logger.isDebugEnabled();
for (Iterator itr = servers.iterator(); itr.hasNext(); ) {
ServerLocation server = (ServerLocation) itr.next();
Connection connection = null;
try {
connection = factory.createClientToServerConnection(server, true);
} catch (GemFireSecurityException e) {
throw e;
} catch (Exception e) {
if (isDebugEnabled) {
logger.debug("SubscriptionManager - Error connecting to server: ()", server, e);
}
}
if (connection == null) {
continue;
}
QueueConnectionImpl queueConnection = initializeQueueConnection(connection, false, null);
if (queueConnection != null) {
boolean isFirstNewConnection = false;
synchronized (lock) {
if (recoverInterest && queueConnections.getPrimary() == null && queueConnections.getBackups().isEmpty()) {
// we lost our queue at some point. We Need to recover
// interest. This server will be made primary after this method
// finishes
// because whoever killed the primary when this method started
// should
// have scheduled a task to recover the primary.
isFirstNewConnection = true;
// TODO - Actually, we need a better check than the above. There's
// still a chance
// that we haven't realized that the primary has died but it is
// already gone. We should
// get some information from the queue server about whether it was
// able to copy the
// queue from another server and decide if we need to recover our
// interest based on
// that information.
}
}
boolean promotionFailed = false;
if (isFirstNewConnection) {
if (!promoteBackupCnxToPrimary(queueConnection)) {
promotionFailed = true;
}
}
if (!promotionFailed) {
if (addToConnectionList(queueConnection, isFirstNewConnection)) {
// redundancy satisfied
printRedundancyNotSatisfiedError = true;
printRecoveringRedundant = true;
if (logger.isDebugEnabled()) {
logger.debug("SubscriptionManager redundancy satisfier - created a queue on server {}", queueConnection.getEndpoint());
}
// redundant server.
if (recoverInterest) {
recoverInterest(queueConnection, isFirstNewConnection);
}
}
}
}
}
}
return true;
}
use of org.apache.geode.security.GemFireSecurityException in project geode by apache.
the class IntegratedSecurityService method getSubject.
/**
* It first looks the shiro subject in AccessControlContext since JMX will use multiple threads to
* process operations from the same client, then it looks into Shiro's thead context.
*
* @return the shiro subject, null if security is not enabled
*/
public Subject getSubject() {
if (!isIntegratedSecurity()) {
return null;
}
Subject currentUser = null;
// First try get the principal out of AccessControlContext instead of Shiro's Thread context
// since threads can be shared between JMX clients.
javax.security.auth.Subject jmxSubject = javax.security.auth.Subject.getSubject(AccessController.getContext());
if (jmxSubject != null) {
Set<ShiroPrincipal> principals = jmxSubject.getPrincipals(ShiroPrincipal.class);
if (principals.size() > 0) {
ShiroPrincipal principal = principals.iterator().next();
currentUser = principal.getSubject();
ThreadContext.bind(currentUser);
return currentUser;
}
}
// in other cases like rest call, client operations, we get it from the current thread
currentUser = SecurityUtils.getSubject();
if (currentUser == null || currentUser.getPrincipal() == null) {
throw new GemFireSecurityException("Error: Anonymous User");
}
return currentUser;
}
Aggregations