/*
After startup everything is a primary and can accept
new nodes into the cluster. This loop accepts the new socket
and passes it off the HostMessenger via the JoinHandler interface
551816
private void runPrimary() throws Exception {
        try {
            // start the server socket on the right interface
            doBind();

            while (true) {
                try {
                    final int selectedKeyCount = m_selector.select();
                    if (selectedKeyCount == 0) {
                        continue;
                    }
                    Set<SelectionKey> selectedKeys = m_selector.selectedKeys();
                    try {
                        for (SelectionKey key : selectedKeys) {
                            processSSC((ServerSocketChannel)key.channel());
                        }
                    } finally {
                        selectedKeys.clear();
                    }
                } catch (ClosedByInterruptException | ClosedSelectorException e) {
                    throw new InterruptedException();
                } catch (Exception e) {
                    LOG.error("Exception occurred in the connection accept loop", e);
                }
            }
        }
        finally {
            for (ServerSocketChannel ssc : m_listenerSockets) {
                try {
                    ssc.close();
                } catch (IOException e) {
                }
            }
            m_listenerSockets.clear();
            try {
                m_selector.close();
            } catch (IOException e) {
            }
            m_selector = null;
        }
    }
1109521
private void doBind() throws Exception {
        LOG.debug("Creating listener socket");
        try {
            m_selector = Selector.open();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        ServerSocketChannel listenerSocket = ServerSocketChannel.open();
        InetSocketAddress inetsockaddr;
        if ((m_internalInterface == null) || (m_internalInterface.length() == 0)) {
            inetsockaddr = new InetSocketAddress(m_internalPort);
        }
        else {
            inetsockaddr = new InetSocketAddress(m_internalInterface, m_internalPort);
        }
        try {
            hostLog.info("Attempting to bind to internal ip " + inetsockaddr);
            listenerSocket.socket().bind(inetsockaddr);
            listenerSocket.configureBlocking(false);
            m_listenerSockets.add(listenerSocket);
        } catch (Exception e) {
            /*
             * If we bound to the leader address, the internal interface address  might not
             * bind if it is all interfaces
             */
            if (m_listenerSockets.isEmpty()) {
                LOG.fatal("Failed to bind to " + inetsockaddr);
                CoreUtils.printPortsInUse(hostLog);
                throw e;
            }
        }

        for (ServerSocketChannel ssc : m_listenerSockets) {
            ssc.register(m_selector, SelectionKey.OP_ACCEPT);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Non-Primary Listening on:" + inetsockaddr.toString());
        }
    }
477779
function (clusterTimeout) {
        if (clusterUrl != null) {
            getServerFromCluster({
                clusterUri : clusterUrl, 
                clusterTimeout : clusterTimeout,
                appKey : ortc.appKey
            }, 
            function (error, body) {
                if (error != null) {
                    delegateExceptionCallback(ortc, 'Error getting server from Cluster');
                }
                else {
                    if (body.indexOf('SOCKET_SERVER') >= 0) {
                        url = body.substring(body.indexOf('=') + 3, body.length - 2);
                        sockjs = createSocketConnection(ortc.getUrl());
                    }
                }
            });
        }
    }
293979
public void startup() {
        if (isRunning) return;

        Executors.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                DispatcherHandler handler = new DispatcherHandler(AndServer.getContext());
                ComponentRegister register = new ComponentRegister(AndServer.getContext());
                register.register(handler, mGroup);

                mHttpServer = ServerBootstrap.bootstrap()
                    .setSocketConfig(SocketConfig.custom()
                        .setSoKeepAlive(true)
                        .setSoReuseAddress(true)
                        .setSoTimeout(mTimeout)
                        .setTcpNoDelay(true)
                        .build())
                    .setConnectionConfig(
                        ConnectionConfig.custom().setBufferSize(4 * 1024).setCharset(Charsets.UTF_8).build())
                    .setLocalAddress(mInetAddress)
                    .setListenerPort(mPort)
                    .setSslContext(mSSLContext)
                    .setSslSetupHandler(new SSLInitializerWrapper(mSSLInitializer))
                    .setServerInfo("AndServer/2.0.0")
                    .registerHandler("*", handler)
                    .setExceptionLogger(ExceptionLogger.NO_OP)
                    .create();
                try {
                    isRunning = true;
                    mHttpServer.start();

                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onStarted();
                        }
                    });
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            mHttpServer.shutdown(3, TimeUnit.SECONDS);
                        }
                    });
                } catch (final Exception e) {
                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onException(e);
                        }
                    });
                }
            }
        });
    }
728421
public void initialize(
            final int clusterIndex,
            final long siteId,
            final int partitionId,
            final int sitesPerHost,
            final int hostId,
            final String hostname,
            final int drClusterId,
            final int defaultDrBufferSize,
            final long tempTableMemory,
            final HashinatorConfig hashinatorConfig,
            final boolean createDrReplicatedStream,
            final long exportFlushTimeout)
    {
        synchronized(printLockObject) {
            System.out.println("Initializing an IPC EE " + this + " for hostId " + hostId + " siteId " + siteId + " from thread " + Thread.currentThread().getId());
        }
        int result = ExecutionEngine.ERRORCODE_ERROR;
        m_data.clear();
        m_data.putInt(Commands.Initialize.m_id);
        m_data.putInt(clusterIndex);
        m_data.putLong(siteId);
        m_data.putInt(partitionId);
        m_data.putInt(sitesPerHost);
        m_data.putInt(hostId);
        m_data.putInt(drClusterId);
        m_data.putInt(defaultDrBufferSize);
        m_data.putLong(EELoggers.getLogLevels());
        m_data.putLong(tempTableMemory);
        m_data.putInt(createDrReplicatedStream ? 1 : 0);
        m_data.putInt((short)hostname.length());
        m_data.put(hostname.getBytes(Charsets.UTF_8));
        try {
            m_data.flip();
            m_connection.write();
            result = m_connection.readStatusByte();
        } catch (final IOException e) {
            System.out.println("Exception: " + e.getMessage());
            throw new RuntimeException(e);
        }
        checkErrorCode(result);
        updateHashinator(hashinatorConfig);
    }
1237376
private SocketChannel createLeaderSocket(
            SocketAddress hostAddr,
            ConnectStrategy mode) throws IOException
    {
        SocketChannel socket;
        int connectAttempts = 0;
        do {
            try {
                socket = SocketChannel.open();
                socket.socket().connect(hostAddr, 5000);
            }
            catch (java.net.ConnectException
                  |java.nio.channels.UnresolvedAddressException
                  |java.net.NoRouteToHostException
                  |java.net.PortUnreachableException e)
            {
                // reset the socket to null for loop purposes
                socket = null;

                if (mode == ConnectStrategy.PROBE) {
                    return null;
                }
                if ((++connectAttempts % 8) == 0) {
                    LOG.warn("Joining primary failed: " + e + " retrying..");
                }
                try {
                    Thread.sleep(250); //  milliseconds
                }
                catch (InterruptedException dontcare) {}
            }
        } while (socket == null);
        return socket;
    }
1017511
@Handler
    public void onStart(Start event) throws IOException {
        closing = false;
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(serverAddress, backlog);
        MBeanView.addServer(this);
        fire(new NioRegistration(this, serverSocketChannel,
            SelectionKey.OP_ACCEPT, this), Channel.BROADCAST);
    }
252588
function init(entry, socket, req) {  // {{{2
/**
 * Class constructor
 *
 * @param entry {Object} Entry of xorg kind
 *
 * @method constructor
 */

  this.entry = entry;

  O.link.open(this, socket);
}
74240
public void init(Cluster cluster, Map<String, Node> nodeIdToNode) {
        _cluster = cluster;
        _nodeIdToNode = nodeIdToNode;
    }
750373
@Override
    public void start() {
        ConnectionPoolMBeanManager.getInstance().registerMonitor(config.getName(), this);

        String seeds = config.getSeeds();
        if (seeds != null && !seeds.isEmpty()) {
            setHosts(config.getSeedHosts());
        }

        config.getLatencyScoreStrategy().start(new Listener() {
            @Override
            public void onUpdate() {
                rebuildPartitions();
            }

            @Override
            public void onReset() {
                rebuildPartitions();
            }
        });
    }
939539
async def register(*address_list, cluster=None, loop=None):
    

    loop = loop or asyncio.get_event_loop()
    for address in address_list:
        host, port = address.rsplit(':', 1)
        node = Node(address=(host, int(port)), loop=loop)
        await node.start()

        for address in cluster:
            host, port = address.rsplit(':', 1)
            port = int(port)

            if (host, port) != (node.host, node.port):
                node.update_cluster((host, port))
101898
function init(options) {
  options = options || {}
  var port = options.port || 6466
  global.client = global.client || socketIOClient(`http://localhost:${port}`)
  client = global.client
  log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)
  client.emit('join', ioid) // first join for serialization
  client.on('disconnect', client.disconnect)
  client.on('take', hasher.handle) // add listener
  
  // add methods
  client.pass = pass
  client.clientPass = clientPass
  return client
}
246017
public void start()
    {
        Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started");

        client.getConnectionStateListenable().addListener(connectionStateListener);
        createNode();
    }
1000006
public void run() {
      /**
        * Ensure we start fresh.
        */
    getLogger().debug("performing socket cleanup prior to entering loop for {}",  name);
    closeServerSocket();
    closeAllAcceptedSockets();
    getLogger().debug("socket cleanup complete for {}", name);       
    active = true;

    // start the server socket
    try {
      serverSocket = new ServerSocket(port);
    } catch (Exception e) {
      getLogger().error(
        "error starting SocketReceiver (" + this.getName()
        + "), receiver did not start", e);
      active = false;
      doShutdown();

      return;
    }

    Socket socket = null;

    try {
      getLogger().debug("in run-about to enter while isactiveloop");

      active = true;

      while (!rThread.isInterrupted()) {
        // if we have a socket, start watching it
        if (socket != null) {
          getLogger().debug("socket not null - creating and starting socketnode");
          socketList.add(socket);

          XMLSocketNode node = new XMLSocketNode(decoder, socket, this);
          node.setLoggerRepository(this.repository);
          new Thread(node).start();
          socket = null;
        }

        getLogger().debug("waiting to accept socket");

        // wait for a socket to open, then loop to start it
        socket = serverSocket.accept();
        getLogger().debug("accepted socket");
      }

      // socket not watched because we a no longer running
      // so close it now.
      if (socket != null) {
        socket.close();
      }
    } catch (Exception e) {
      getLogger().warn(
        "socket server disconnected, stopping");
    }
  }
52754
public void init(SocketChannel s)
  {
    _s = s;

    try {
      s.setOption(StandardSocketOptions.TCP_NODELAY, true);
    } catch (Exception e) {
      e.printStackTrace();;
    }
    //_is = null;
    //_os = null;
    _needsFlush = false;
    
    _readBuffer.clear().flip();
    _writeBuffer.clear();
  }
777345
public synchronized void refreshNodes() throws IOException {
    hostsReader.refresh();
    LOG.info("After refresh Included hosts: " +
        hostsReader.getHostNames().size() +
        " Excluded hosts: " + hostsReader.getExcludedHosts().size());
    Set<String> newHosts = hostsReader.getHostNames();
    Set<String> newExcludes = hostsReader.getExcludedHosts();
    Set<ClusterNode> hostsToExclude = new HashSet<ClusterNode>();
    for (ClusterNode tmpNode : nameToNode.values()) {
      String host = tmpNode.getHost();
      // Check if not included or explicitly excluded.
      if (!newHosts.contains(host) || newExcludes.contains(host)) {
        hostsToExclude.add(tmpNode);
      }
    }
    for (ClusterNode node: hostsToExclude) {
      synchronized (node) {
        for (Map.Entry<ResourceType, RunnableIndices> entry :
          typeToIndices.entrySet()) {
          ResourceType type = entry.getKey();
          RunnableIndices r = entry.getValue();
          if (r.hasRunnable(node)) {
            LOG.info("Node " + node.getName() + " is no longer " +
              type + " runnable because it is excluded");
            r.deleteRunnable(node);
          }
        }
      }
    }
  }
1017202
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) {

		// Get the list of tokens for these hosts
		//tokenSupplier.initWithHosts(hPools.keySet());
		List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet());
		Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>();
	        
		// Update inner state with the host tokens.
		for (HostToken hToken : allHostTokens) {
			hostTokens.put(hToken.getHost(), hToken);
			tokenPoolMap.put(hToken, hPools.get(hToken.getHost()));
		}

		// Initialize Local selector
		Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForRack(tokenPoolMap, localRack);
		localSelector.initWithHosts(localPools);
		if (localSelector.isTokenAware() && localRack != null) {
		   replicationFactor.set(calculateReplicationFactor(allHostTokens));
		}

		// Initialize Remote selectors
		Set<String> remoteRacks = new HashSet<String>();
		for (Host host : hPools.keySet()) {
			String rack = host.getRack();
			if (localRack != null && !localRack.isEmpty() && rack != null && !rack.isEmpty() && !localRack.equals(rack)) {
				remoteRacks.add(rack);
			}
		}

		for (String rack : remoteRacks) {
			Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForRack(tokenPoolMap, rack);
			HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy();
			remoteSelector.initWithHosts(dcPools);
			remoteRackSelectors.put(rack, remoteSelector);
		}

		remoteDCNames.swapWithList(remoteRackSelectors.keySet());

        topology.set(createTokenPoolTopology(allHostTokens));
	}