Search in sources :

Example 1 with ResourceHandle

use of com.sun.enterprise.resource.ResourceHandle in project Payara by payara.

the class AssocWithThreadPoolResizer method removeIdleAndInvalidResources.

/**
 * Get the free connections list from the pool, remove idle-timed-out resources
 * and then invalid resources.
 *
 * @return int number of resources removed
 */
@Override
protected int removeIdleAndInvalidResources() {
    int poolSizeBeforeRemoval = ds.getResourcesSize();
    int noOfResourcesRemoved = 0;
    // let's cache the current time since precision is not required here.
    long currentTime = System.currentTimeMillis();
    int validConnectionsCounter = 0;
    int idleConnKeptInSteadyCounter = 0;
    ResourceState state;
    Set<ResourceHandle> resourcesToValidate = new HashSet<ResourceHandle>();
    Set<ResourceHandle> resourcesToRemove = new HashSet<ResourceHandle>();
    try {
        // iterate through all the resources to find idle-time lapsed ones.
        for (ResourceHandle h : ds.getAllResources()) {
            synchronized (h.lock) {
                state = h.getResourceState();
                if (!state.isBusy()) {
                    if (currentTime - state.getTimestamp() < pool.getIdleTimeout()) {
                        // Should be added for validation.
                        if (state.isUnenlisted() && state.isFree()) {
                            if (((AssocWithThreadResourceHandle) h).isAssociated()) {
                                ((AssocWithThreadResourceHandle) h).setAssociated(false);
                                validConnectionsCounter++;
                                resourcesToValidate.add(h);
                            }
                        }
                    } else {
                        boolean isResourceEligibleForRemoval = isResourceEligibleForRemoval(h, validConnectionsCounter);
                        if (!isResourceEligibleForRemoval) {
                            // preferValidateOverrecreate true and connection is valid within SPS
                            validConnectionsCounter++;
                            idleConnKeptInSteadyCounter++;
                            debug("PreferValidateOverRecreate: Keeping idle resource " + h + " in the steady part of the free pool " + "as the RA reports it to be valid (" + validConnectionsCounter + " <= " + pool.getSteadyPoolSize() + ")");
                        } else {
                            // Add this to remove later
                            resourcesToRemove.add(h);
                            ((AssocWithThreadResourceHandle) h).setDirty();
                        }
                    }
                }
            }
        }
    } finally {
        for (ResourceHandle resourceToRemove : resourcesToRemove) {
            if (ds.getAllResources().contains(resourceToRemove)) {
                ds.removeResource(resourceToRemove);
            }
        }
    }
    // remove invalid resources from the free (active) resources list.
    // Since the whole pool is not locked, it may happen that some of these
    // resources may be given to applications.
    int noOfInvalidResources = removeInvalidResources(resourcesToValidate);
    // locks the pool throughout its operations.
    if (preferValidateOverRecreate) {
        debug("Idle resources validated and kept in the steady pool for pool [ " + poolInfo + " ] - " + idleConnKeptInSteadyCounter);
        debug("Number of Idle resources freed for pool [ " + poolInfo + " ] - " + (resourcesToRemove.size()));
        debug("Number of Invalid resources removed for pool [ " + poolInfo + " ] - " + noOfInvalidResources);
    } else {
        debug("Number of Idle resources freed for pool [ " + poolInfo + " ] - " + resourcesToRemove.size());
        debug("Number of Invalid resources removed for pool [ " + poolInfo + " ] - " + noOfInvalidResources);
    }
    noOfResourcesRemoved = poolSizeBeforeRemoval - ds.getResourcesSize();
    return noOfResourcesRemoved;
}
Also used : ResourceHandle(com.sun.enterprise.resource.ResourceHandle) AssocWithThreadResourceHandle(com.sun.enterprise.resource.AssocWithThreadResourceHandle) ResourceState(com.sun.enterprise.resource.ResourceState) HashSet(java.util.HashSet) AssocWithThreadResourceHandle(com.sun.enterprise.resource.AssocWithThreadResourceHandle)

Example 2 with ResourceHandle

use of com.sun.enterprise.resource.ResourceHandle in project Payara by payara.

the class AssocWithThreadPoolResizer method removeInvalidResources.

/**
 * Removes invalid resource handles in the pool while resizing the pool.
 * Uses the Connector 1.5 spec 6.5.3.4 optional RA feature to obtain
 * invalid ManagedConnections
 *
 * @param freeConnectionsToValidate Set of free connections
 */
private int removeInvalidResources(Set<ResourceHandle> freeConnectionsToValidate) {
    int invalidConnectionsCount = 0;
    try {
        debug("Sending a set of free connections to RA, " + "of size : " + freeConnectionsToValidate.size());
        try {
            for (ResourceHandle handle : freeConnectionsToValidate) {
                if (handle != null) {
                    Set connectionsToTest = new HashSet();
                    connectionsToTest.add(handle.getResource());
                    Set invalidConnections = handler.getInvalidConnections(connectionsToTest);
                    if (invalidConnections != null && invalidConnections.size() > 0) {
                        invalidConnectionsCount = validateAndRemoveResource(handle, invalidConnections);
                    } else {
                    // valid resource
                    }
                }
            }
        } finally {
            debug("No. of invalid connections received from RA : " + invalidConnectionsCount);
        }
    } catch (ResourceException re) {
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "ResourceException while trying to get invalid connections from MCF", re);
        }
    } catch (Exception e) {
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "Exception while trying to get invalid connections from MCF", e);
        }
    }
    return invalidConnectionsCount;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ResourceHandle(com.sun.enterprise.resource.ResourceHandle) AssocWithThreadResourceHandle(com.sun.enterprise.resource.AssocWithThreadResourceHandle) ResourceException(javax.resource.ResourceException) ResourceException(javax.resource.ResourceException) HashSet(java.util.HashSet)

Example 3 with ResourceHandle

use of com.sun.enterprise.resource.ResourceHandle in project Payara by payara.

the class ConnectionLeakDetector method clearAllConnectionLeakTasks.

/**
 * Clear all connection leak tracing tasks in case of connection leak
 * tracing being turned off
 */
private void clearAllConnectionLeakTasks() {
    synchronized (connectionLeakLock) {
        for (ResourceHandle resourceHandle : connectionLeakTimerTaskHashMap.keySet()) {
            ConnectionLeakTask connectionLeakTask = connectionLeakTimerTaskHashMap.get(resourceHandle);
            connectionLeakTask.cancel();
        }
        if (getTimer() != null)
            getTimer().purge();
        connectionLeakThreadStackHashMap.clear();
        connectionLeakTimerTaskHashMap.clear();
    }
}
Also used : ResourceHandle(com.sun.enterprise.resource.ResourceHandle)

Example 4 with ResourceHandle

use of com.sun.enterprise.resource.ResourceHandle in project Payara by payara.

the class ConnectionPool method getResourceFromTransaction.

/**
 * Try to get a resource from current transaction if it is shareable<br>
 * @param tran Current Transaction
 * @param alloc ResourceAllocator
 * @param spec ResourceSpec
 * @return result ResourceHandle
 */
private ResourceHandle getResourceFromTransaction(Transaction tran, ResourceAllocator alloc, ResourceSpec spec) {
    ResourceHandle result = null;
    try {
        // shareable, so abort right here if that's not the case
        if (tran != null && alloc.shareableWithinComponent()) {
            // TODO should be handled by PoolTxHelper
            JavaEETransaction j2eetran = (JavaEETransaction) tran;
            // case 1. look for free and enlisted in same tx
            Set set = j2eetran.getResources(poolInfo);
            if (set != null) {
                Iterator iter = set.iterator();
                while (iter.hasNext()) {
                    ResourceHandle h = (ResourceHandle) iter.next();
                    if (h.hasConnectionErrorOccurred()) {
                        iter.remove();
                        continue;
                    }
                    ResourceState state = h.getResourceState();
                    /*
                         * One can share a resource only for the following conditions:
                         * 1. The caller resource is shareable (look at the outermost
                         *    if marked comment-1
                         * 2. The resource enlisted inside the transaction is shareable
                         * 3. We are dealing with XA resources OR
                         *    We are dealing with a non-XA resource that's not in use
                         *    Note that sharing a non-xa resource that's in use involves
                         *    associating physical connections.
                         * 4. The credentials of the resources match
                         */
                    if (h.getResourceAllocator().shareableWithinComponent()) {
                        if (spec.isXA() || poolTxHelper.isNonXAResourceAndFree(j2eetran, h)) {
                            if (matchConnections) {
                                if (!alloc.matchConnection(h)) {
                                    if (poolLifeCycleListener != null) {
                                        poolLifeCycleListener.connectionNotMatched();
                                    }
                                    continue;
                                }
                                if (h.hasConnectionErrorOccurred()) {
                                    if (failAllConnections) {
                                        // if failAllConnections has happened, we flushed the
                                        // pool, so we don't have to do iter.remove else we
                                        // will get a ConncurrentModificationException
                                        result = null;
                                        break;
                                    }
                                    iter.remove();
                                    continue;
                                }
                                if (poolLifeCycleListener != null) {
                                    poolLifeCycleListener.connectionMatched();
                                }
                            }
                            if (state.isFree())
                                setResourceStateToBusy(h);
                            result = h;
                            break;
                        }
                    }
                }
            }
        }
    } catch (ClassCastException e) {
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "Pool: getResource : " + "transaction is not JavaEETransaction but a " + tran.getClass().getName(), e);
        }
    }
    return result;
}
Also used : JavaEETransaction(com.sun.enterprise.transaction.api.JavaEETransaction) ResourceHandle(com.sun.enterprise.resource.ResourceHandle) ResourceState(com.sun.enterprise.resource.ResourceState)

Example 5 with ResourceHandle

use of com.sun.enterprise.resource.ResourceHandle in project Payara by payara.

the class ConnectionPool method resizePoolAndGetNewResource.

/**
 * Scale-up the pool to serve the new request. <br>
 * If pool is at max-pool-size and free resources are found, purge unmatched<br>
 * resources, create new connections and serve the request.<br>
 *
 * @param alloc ResourceAllocator used to create new resources
 * @return ResourceHandle newly created resource
 * @throws PoolingException when not able to create resources
 */
private ResourceHandle resizePoolAndGetNewResource(ResourceAllocator alloc) throws PoolingException {
    // Must be called from the thread holding the lock to this pool.
    ResourceHandle result = null;
    int numOfConnsToCreate = 0;
    if (ds.getResourcesSize() < steadyPoolSize) {
        // May be all invalid resources are destroyed as
        // a result no free resource found and no. of resources is less than steady-pool-size
        numOfConnsToCreate = steadyPoolSize - ds.getResourcesSize();
    } else if (ds.getResourcesSize() + resizeQuantity <= maxPoolSize) {
        // Create and add resources of quantity "resizeQuantity"
        numOfConnsToCreate = resizeQuantity;
    } else if (ds.getResourcesSize() < maxPoolSize) {
        // This else if "test condition" is not needed. Just to be safe.
        // still few more connections (less than "resizeQuantity" and to reach the count of maxPoolSize)
        // can be added
        numOfConnsToCreate = maxPoolSize - ds.getResourcesSize();
    }
    if (numOfConnsToCreate > 0) {
        createResources(alloc, numOfConnsToCreate);
        result = getMatchedResourceFromPool(alloc);
    } else if (ds.getFreeListSize() > 0) {
        // of size <=resizeQuantity
        if (purgeResources(resizeQuantity) > 0) {
            result = resizePoolAndGetNewResource(alloc);
        }
    }
    return result;
}
Also used : ResourceHandle(com.sun.enterprise.resource.ResourceHandle)

Aggregations

ResourceHandle (com.sun.enterprise.resource.ResourceHandle)36 PoolingException (com.sun.appserv.connectors.internal.api.PoolingException)11 ResourceException (javax.resource.ResourceException)9 ResourceState (com.sun.enterprise.resource.ResourceState)6 JavaEETransaction (com.sun.enterprise.transaction.api.JavaEETransaction)5 HashSet (java.util.HashSet)5 AssocWithThreadResourceHandle (com.sun.enterprise.resource.AssocWithThreadResourceHandle)4 ManagedConnection (javax.resource.spi.ManagedConnection)3 RetryableUnavailableException (javax.resource.spi.RetryableUnavailableException)3 ResourceSpec (com.sun.enterprise.resource.ResourceSpec)2 JavaEETransactionManager (com.sun.enterprise.transaction.api.JavaEETransactionManager)2 Set (java.util.Set)2 InvocationException (org.glassfish.api.invocation.InvocationException)2 ConnectorRuntimeException (com.sun.appserv.connectors.internal.api.ConnectorRuntimeException)1 XAResourceWrapper (com.sun.enterprise.resource.XAResourceWrapper)1 ConnectionEventListener (com.sun.enterprise.resource.listener.ConnectionEventListener)1 PoolManager (com.sun.enterprise.resource.pool.PoolManager)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Iterator (java.util.Iterator)1 List (java.util.List)1