Terminate all the connections associated with the chain

@param chainName
@throws Exception
772593
public void terminateConnectionsAssociatedWithChain(String chainName) throws Exception {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(this, tc, "terminateConnectionsAssociatedWithChain", chainName);

        synchronized (endPointToGroupMap) {

            try {
                final HashMap<EndPointDescriptor, ConnectionDataGroup> endPointToGroupMapClone = (HashMap<EndPointDescriptor, ConnectionDataGroup>) endPointToGroupMap.clone();
                Iterator<EndPointDescriptor> it = endPointToGroupMapClone.keySet().iterator();
                while (it.hasNext()) {
                    EndPointDescriptor ed = it.next();

                    if ((((HostPortEndPointDescriptor) ed).chainName).equals(chainName)) {

                        ConnectionDataGroup cdGroup = endPointToGroupMapClone.get(ed);

                        final List connectionData = cdGroup.getConnections();

                        for (final Iterator connectionDataIterator = connectionData.iterator(); connectionDataIterator.hasNext();)
                        {
                            final ConnectionData thisConnectionData = (ConnectionData) connectionDataIterator.next();
                            final OutboundConnection oc = thisConnectionData.getConnection();
                            //close all the conservations associated with the OC
                            Conversation[] conv = oc.getConversations();
                            for (Conversation c : conv) {
                                try {
                                    c.fastClose();
                                } catch (Exception e) {//Don't let the exception mess up closing other remaining conservations
                                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                        SibTr.debug(tc, "Error while fast closing the conversation", e);
                                }

                            }
                            try {
                                // terminate the physical connection
                                purgeFromInvalidateImpl(oc, false);
                            } catch (Exception e) {//Don't let the exception mess up closing other remaining connection
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                    SibTr.debug(tc, "Error while purging the physical connection", e);
                            }
                        }

                        try {
                            // destroy the OutboundVirtualConnection associated with the chainName
                            cdGroup.getNetworkConnectionFactory().getOutboundVirtualConFactory().destroy();
                        } catch (Exception e) {//Don't let the exception mess up closing other remaining connection
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                SibTr.debug(tc, "Error while destroying the outbound virtual connection", e);
                        }
                        // in fastClose() the entry is removed but still we do a remove 
                        endPointToGroupMap.remove(ed);

                    }
                }

            } catch (Exception e) {
                throw e;
            } finally {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    Tr.exit(this, tc, "terminateConnectionsAssociatedWithChain");
            }

        }
    }
826349
public synchronized void clear() throws ChannelException, ChainException, ChainGroupException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "clear");
        }

        StringBuilder sbErrors = new StringBuilder();

        // Stop destroy and remove all running chains.
        Chain[] chains = chainRunningMap.values().toArray(new Chain[chainRunningMap.size()]);
        for (int i = 0; i < chains.length; i++) {
            Chain chain = chains[i];
            if (chain.getState() == RuntimeState.STARTED || chain.getState() == RuntimeState.QUIESCED) {
                try {
                    stopChainInternal(chain, 0);
                } catch (Exception e) {
                    FFDCFilter.processException(e, getClass().getName() + ".clear", "322", this, new Object[] { chain, this });
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Caught stopChainInternal exception " + e.getMessage());
                    }
                    sbErrors.append(e.toString());
                }
            }
            try {
                destroyChainInternal(chain);
            } catch (ChannelException e) {
                // FFDC handled in destroyChainInternal.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught destroyChainInternal exception " + e.getMessage());
                }
                sbErrors.append(e.toString());
            } catch (ChainException e) {
                // FFDC handled in destroyChainInternal.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught destroyChainInternal exception " + e.getMessage());
                }
                sbErrors.append(e.toString());
            } catch (Exception e) {
                FFDCFilter.processException(e, getClass().getName() + ".clear", "329", this, new Object[] { chain, this });
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught destroyChainInternal exception " + e.getMessage());
                }
                sbErrors.append(e.toString());
            }
            try {
                removeChain(chain.getName());
            } catch (Exception e) {
                FFDCFilter.processException(e, getClass().getName() + ".clear", "335", this, new Object[] { chain, this });
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught removeChain exception " + e.getMessage());
                }
                sbErrors.append(e.toString());
            }
        }
        this.chainRunningMap.clear();
        this.channelRunningMap.clear();

        // Remove all chain groups
        String[] keys = chainGroups.keySet().toArray(new String[chainGroups.size()]);
        for (int i = 0; i < keys.length; i++) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Remove chainGroup, " + keys[i]);
            }
            try {
                removeChainGroup(keys[i]);
            } catch (Exception e) {
                FFDCFilter.processException(e, getClass().getName() + ".clear", "351", this, new Object[] { keys[i], this });
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught removeChainGroup exception " + e.getMessage());
                }
                sbErrors.append(e.toString());
            }
        }
        this.chainGroups.clear();

        // Remove all channels.
        keys = channelDataMap.keySet().toArray(new String[channelDataMap.size()]);
        for (int i = 0; i < keys.length; i++) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Remove channelData, " + keys[i]);
            }
            try {
                String name = keys[i];
                if (name != null)
                    removeChannel(name);
            } catch (Exception e) {
                FFDCFilter.processException(e, getClass().getName() + ".clear", "366", this, new Object[] { keys[i], this });
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught removeChannel exception " + e.getMessage());
                }
                sbErrors.append(e.toString());
            }
        }
        this.channelDataMap.clear();
        this.chainDataMap.clear();

        // Destroy all channel factories
        Class<?>[] factoryList = channelFactories.keySet().toArray(new Class<?>[channelFactories.size()]);
        for (Class<?> target : factoryList) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Remove channelFactory, " + target);
            }
            ChannelFactory factory = channelFactories.remove(target).getChannelFactory();
            if (factory != null) {
                try {
                    factory.destroy();
                } catch (Exception e) {
                    FFDCFilter.processException(e, getClass().getName() + ".clear", "384", this, new Object[] { factory, this });
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Caught factory.destroy exception " + e.getMessage());
                    }
                    sbErrors.append(e.toString());
                }
            }
        }
        this.channelFactories.clear();

        // Clear the chain event listeners
        this.globalChainEventListeners.clear();

        // Clear out the services.
        this.services.clear();

        // Check if an error occurred.
        if (sbErrors.length() > 0) {
            // Found an error. Throw an exception containing all the details of the
            // errors caught.
            throw new ChannelException(sbErrors.toString());
        }

        this.activatedProviders.clear();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "clear");
        }
    }
85722
public void stop() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "CommsInboundChain Stop");

        //stopchain() first quiesce's(invokes chainQuiesced) depending on the chainQuiesceTimeOut
        //Once the chain is quiesced StopChainTask is initiated.Hence we block until the actual stopChain is invoked
        try {
            ChainData cd = _cfw.getChain(_chainName);
            if (cd != null) {
                _cfw.stopChain(cd, _cfw.getDefaultChainQuiesceTimeout());
                stopWait.waitForStop(_cfw.getDefaultChainQuiesceTimeout()); //BLOCK till stopChain actually completes from StopChainTask
                _cfw.destroyChain(cd);
                _cfw.removeChain(cd);
            }
        } catch (Exception e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "Failed in successfully cleaning(i.e stopping/destorying/removing) chain: ", e);
        } finally {
            _isChainStarted = false;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "CommsServerServiceFacade JfapChainStop");
    }
903881
public void terminateAllConnections(){
		this.terminationLock.lock();
		try{
			// close off all connections.
			for (int i=0; i < this.pool.partitionCount; i++) {
				this.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization
				List<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); 
				this.pool.partitions[i].getFreeConnections().drainTo(clist);
				for (ConnectionHandle c: clist){
					this.pool.destroyConnection(c);
				}

			}
		} finally {
			this.terminationLock.unlock();
		}
	}
598685
public void close() throws Exception {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }
856567
public void close() throws IOException, InterruptedException {
    LOG.debug("closing connection");
    stream.close();
    uplink.closeConnection();
    uplink.interrupt();
    uplink.join();
  }
1012444
public void stopConnection() throws CommunicationException, KeystoreException {
		processedFailedNotifications();
		try {
			logger.debug("Closing connection");
			this.socket.close();
		} catch (Exception e) {
			/* Do not complain if connection is already closed... */
		}
	}
1199078
@Override
	public void terminateAllConnections() {
		this.terminationLock.lock();
		try {
			for (int i = 0; i < this.pool.thriftServerCount; i++) {
				this.pool.partitions.get(i).setUnableToCreateMoreTransactions(false);
				List<ThriftConnectionHandle<T>> clist = new LinkedList<>();
				this.pool.partitions.get(i).getFreeConnections().drainTo(clist);
				for (ThriftConnectionHandle<T> c : clist) {
					this.pool.destroyConnection(c);
				}

			}
		} finally {
			this.terminationLock.unlock();
		}
	}
1355781
public synchronized void stop() throws Exception {
		if (this.serverChannel != null) {
			this.serverChannel.close().awaitUninterruptibly();
			this.serverChannel = null;
		}
		if (bootstrap != null) {
			if (bootstrap.group() != null) {
				bootstrap.group().shutdownGracefully();
			}
			bootstrap = null;
		}
	}
358293
@Override
    public void stop() throws Exception {
        if (!this.started) {
            logger.warn(String.format("management=%s is already stopped", this.name));
            return;
        }

        // this.nettyClientOpsThread.setStarted(false);

        for (ManagementEventListener lstr : managementEventListeners) {
            try {
                lstr.onServiceStopped();
            } catch (Throwable ee) {
                logger.error("Exception while invoking onServiceStopped", ee);
            }
        }

        // We store the original state first
        this.store();

        // Stop all associations
        FastMap<String, Association> associationsTemp = this.associations;
        for (FastMap.Entry<String, Association> n = associationsTemp.head(), end = associationsTemp.tail(); (n = n.getNext()) != end;) {
            Association associationTemp = n.getValue();
            if (associationTemp.isStarted()) {
                ((NettyAssociationImpl) associationTemp).stop();
            }
        }

        FastList<Server> tempServers = servers;
        for (FastList.Node<Server> n = tempServers.head(), end = tempServers.tail(); (n = n.getNext()) != end;) {
            Server serverTemp = n.getValue();
            if (serverTemp.isStarted()) {
                try {
                    ((NettyServerImpl) serverTemp).stop();
                } catch (Exception e) {
                    logger.error(String.format("Exception while stopping the Server=%s", serverTemp.getName()), e);
                }
            }
        }

        // waiting till stopping associations
        for (int i1 = 0; i1 < 20; i1++) {
            boolean assConnected = false;
            for (FastMap.Entry<String, Association> n = this.associations.head(), end = this.associations.tail(); (n = n
                    .getNext()) != end;) {
                Association associationTemp = n.getValue();
                if (associationTemp.isConnected()) {
                    assConnected = true;
                    break;
                }
            }
            if (!assConnected)
                break;
            Thread.sleep(100);
        }

        // TODO - make a general shutdown and waiting for it instead of "waiting till stopping associations" 
        this.bossGroup.shutdownGracefully();
        this.workerGroup.shutdownGracefully();
        this.clientExecutor.shutdown();
       

        // TODO Should servers be also checked for shutdown?

        this.started = false;

    }
894798
@Override
    public synchronized ChainData removeChain(String chainName) throws ChainException {
        String entryMsg = "removeChain: " + chainName;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, entryMsg);
        }
        if (null == chainName) {
            throw new InvalidChainNameException("Input chain name is null");
        }

        // Look for runtime chains.
        Chain chain = chainRunningMap.get(chainName);
        if (chain != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                // Due to timing windows (i.e. multiple channel providers going away), there is
                // a race to stop and/or clean up chains. This is not a notable condition: the chain can only be removed
                // once.
                Tr.exit(tc, entryMsg, "Chain not found");
            }
            return null;
        }

        // Find the chain config
        ChainData chainData = chainDataMap.get(chainName);
        if (null == chainData) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                // Due to timing windows (i.e. multiple channel providers going away), there is
                // a race to stop and/or clean up chains. This is not a notable condition: the chain can only be removed
                // once.
                Tr.exit(tc, entryMsg, "ChainData not found");
            }
            return null;
        }
        removeChainInternal(chainData);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, entryMsg);
        }
        return chainData;
    }
1121690
@Override
    public void stop(BundleContext bc) throws Exception {
        RuntimeDelegate.setInstance(null);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "stop", bc);
        }
    }
118929
public void releaseAndTryRemoveAll() throws Exception {
		Collection<String> children = getAllPaths();

		Exception exception = null;

		for (String child : children) {
			try {
				releaseAndTryRemove('/' + child);
			} catch (Exception e) {
				exception = ExceptionUtils.firstOrSuppressed(e, exception);
			}
		}

		if (exception != null) {
			throw new Exception("Could not properly release and try removing all state nodes.", exception);
		}
	}
148340
@Override
	public void close() {
		try {
			connection.close();
		} catch(IOException e) {
			log.log(Level.WARNING, "Could not close connection", e);
		}
	}
1076927
private static void unloadChains(Iterator<String> chains) {
        final boolean bTrace = TraceComponent.isAnyTracingEnabled();
        final ChannelFramework cf = ChannelFrameworkFactory.getChannelFramework();

        List<String> runningChains = new LinkedList<String>();
        while (chains.hasNext()) {
            ChainData cd = cf.getChain(chains.next());
            if (null != cd && FlowType.INBOUND.equals(cd.getType())) {
                if (bTrace && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Unloading chain; " + cd.getName());
                }
                try {
                    if (cf.isChainRunning(cd)) {
                        runningChains.add(cd.getName());
                    } else {
                        cf.destroyChain(cd);
                        cf.removeChain(cd);
                    }
                } catch (Exception e) {
                    FFDCFilter.processException(e, "ChannelUtils",
                                                "unloadChains", new Object[] { cd, cf });
                    if (bTrace && tc.isEventEnabled()) {
                        Tr.event(tc, "Unable to remove chain; " + cd.getName());
                    }
                }
            }
        }

        // Stop chains, and wait for stop to complete...
        stopChains(runningChains, -1L, null);
        for (String name : runningChains) {
            ChainData cd = cf.getChain(name);
            if (bTrace && tc.isDebugEnabled()) {
                Tr.debug(tc, "Unloading stopped chain; " + name);
            }
            try {
                cf.destroyChain(cd);
                cf.removeChain(cd);
            } catch (Exception e) {
                FFDCFilter.processException(e, "ChannelUtils", "unloadChains",
                                            new Object[] { cd, cf });
                if (bTrace && tc.isEventEnabled()) {
                    Tr.event(tc, "Unable to remove chain; " + name);
                }
            }
        }
    }
151731
@Override
    public void close(ClusterName clusterName) {
        logger.info("Close connection to cluster [" + clusterName + "] from connector [" + this.getClass().getSimpleName()  + "]");
        connectionHandler.closeConnection(clusterName.getName());

    }
944452
@Override
    public boolean close () throws CIFSException {
        boolean inUse = false;
        
        List<SmbTransportImpl> toClose;
        synchronized ( this.connections ) {
            log.debug("Closing pool");
            toClose = new LinkedList<>(this.connections);
            toClose.addAll(this.nonPooledConnections);
            this.connections.clear();
            this.nonPooledConnections.clear();
        }
        for ( SmbTransportImpl conn : toClose ) {
            try {
                inUse |= conn.disconnect(false, false);
            }
            catch ( IOException e ) {
                log.warn("Failed to close connection", e);
            }
        }
        return inUse;
    }