use of java.nio.channels.SocketChannel in project openhab1-addons by openhab.
the class CULNetworkHandlerImpl method processConnect.
private void processConnect(SelectionKey key) throws Exception {
SocketChannel ch = (SocketChannel) key.channel();
if (ch.finishConnect()) {
key.interestOps(key.interestOps() ^ SelectionKey.OP_CONNECT);
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
reconnectInterval = INITIAL_RECONNECT_INTERVAL;
connected.set(true);
onConnected();
}
}
use of java.nio.channels.SocketChannel in project voltdb by VoltDB.
the class SocketJoiner method requestForConnection.
public SocketChannel requestForConnection(InetSocketAddress hostAddr) throws IOException, JSONException {
SocketChannel socket = connectToHost(hostAddr);
/*
* Get the clock skew value
*/
ByteBuffer currentTimeBuf = ByteBuffer.allocate(8);
while (currentTimeBuf.hasRemaining()) {
socket.read(currentTimeBuf);
}
assert currentTimeBuf.position() == 8 : "time buffer is at an unexpected position";
JSONObject jsObj = new JSONObject();
jsObj.put(TYPE, ConnectionType.REQUEST_CONNECTION.name());
jsObj.put(VERSION_STRING, m_acceptor.getVersionChecker().getVersionString());
jsObj.put(HOST_ID, m_localHostId);
jsObj.put(PORT, m_internalPort);
jsObj.put(ADDRESS, m_internalInterface.isEmpty() ? m_reportedInternalInterface : m_internalInterface);
byte[] jsBytes = jsObj.toString(4).getBytes(StandardCharsets.UTF_8);
ByteBuffer addConnection = ByteBuffer.allocate(4 + jsBytes.length);
addConnection.putInt(jsBytes.length);
addConnection.put(jsBytes).flip();
while (addConnection.hasRemaining()) {
socket.write(addConnection);
}
// read the json response from socketjoiner with version info and validate it
final String remoteAddress = socket.socket().getRemoteSocketAddress().toString();
processJSONResponse(socket, remoteAddress, null, false);
return socket;
}
use of java.nio.channels.SocketChannel in project voltdb by VoltDB.
the class RegressionSuite method tearDown.
/**
* JUnit special method called to shutdown the test. This instance will
* stop the VoltDB server using the VoltServerConfig instance provided.
*/
@Override
public void tearDown() throws Exception {
if (m_completeShutdown) {
m_config.shutDown();
} else {
Catalog currentCataog = getCurrentCatalog();
if (currentCataog != null) {
CatalogDiffEngine diff = new CatalogDiffEngine(m_config.getInitialCatalog(), currentCataog);
// We will ignore this case.
if (diff.commands().split("\n").length > 1) {
fail("Catalog changed in test " + getName() + " while the regression suite optimization is on: \n" + diff.getDescriptionOfChanges(false));
}
}
Client client = getClient();
VoltTable tableList = client.callProcedure("@SystemCatalog", "TABLES").getResults()[0];
ArrayList<String> tableNames = new ArrayList<>(tableList.getRowCount());
int tableNameColIdx = tableList.getColumnIndex("TABLE_NAME");
int tableTypeColIdx = tableList.getColumnIndex("TABLE_TYPE");
while (tableList.advanceRow()) {
String tableType = tableList.getString(tableTypeColIdx);
if (!tableType.equalsIgnoreCase("EXPORT")) {
tableNames.add(tableList.getString(tableNameColIdx));
}
}
for (String tableName : tableNames) {
try {
client.callProcedure("@AdHoc", "DELETE FROM " + tableName);
} catch (ProcCallException pce) {
if (!pce.getMessage().contains("Illegal to modify a materialized view.")) {
fail("Hit an exception when cleaning up tables between tests: " + pce.getMessage());
}
}
}
client.drain();
}
for (final Client c : m_clients) {
c.close();
}
synchronized (m_clientChannels) {
for (final SocketChannel sc : m_clientChannels) {
try {
ConnectionUtil.closeConnection(sc);
} catch (final IOException e) {
e.printStackTrace();
}
}
m_clientChannels.clear();
}
m_clients.clear();
}
use of java.nio.channels.SocketChannel in project voltdb by VoltDB.
the class TestMaliciousClientSuite method testManyClientsComingAndGoing.
@org.junit.Test
public void testManyClientsComingAndGoing() throws Exception {
for (int ii = 0; ii < 2000; ii++) {
ArrayList<SocketChannel> channels = new ArrayList<SocketChannel>();
for (int zz = 0; zz < 100; zz++) {
channels.add(getClientChannel(true));
}
for (SocketChannel sc : channels) {
sc.close();
}
System.out.printf("Ran through testManyClientsComingAndGoing loop %d times.\n", ii);
System.out.flush();
}
}
use of java.nio.channels.SocketChannel in project voltdb by VoltDB.
the class SocketJoiner method connectToPrimary.
/*
* If this node failed to bind to the leader address
* it must connect to the leader which will generate a host id and
* advertise the rest of the cluster so that connectToPrimary can connect to it
*/
private void connectToPrimary(InetSocketAddress coordIp, ConnectStrategy mode) throws Exception {
// collect clock skews from all nodes
List<Long> skews = new ArrayList<Long>();
// collect the set of active voltdb version strings in the cluster
// this is used to limit simulatanious versions to two
Set<String> activeVersions = new TreeSet<String>();
try {
LOG.debug("Non-Primary Starting & Connecting to Primary");
SocketChannel socket = createLeaderSocket(coordIp, mode);
// in probe mode
if (socket == null)
return;
if (!coordIp.equals(m_coordIp)) {
m_coordIp = coordIp;
}
socket.socket().setTcpNoDelay(true);
socket.socket().setPerformancePreferences(0, 2, 1);
// blocking call, send a request to the leader node and get a host id assigned by the leader
RequestHostIdResponse response = requestHostId(socket, skews, activeVersions);
// check if the membership request is accepted
JSONObject responseBody = response.getResponseBody();
if (!responseBody.optBoolean(ACCEPTED, true)) {
socket.close();
if (!responseBody.optBoolean(MAY_RETRY, false)) {
org.voltdb.VoltDB.crashLocalVoltDB("Request to join cluster is rejected: " + responseBody.optString(REASON, "rejection reason is not available"));
}
throw new CoreUtils.RetryException(responseBody.optString(REASON, "rejection reason is not available"));
}
/*
* Get the generated host id, and the interface we connected on
* that was echoed back
*/
m_localHostId = responseBody.getInt(NEW_HOST_ID);
m_reportedInternalInterface = responseBody.getString(REPORTED_ADDRESS);
ImmutableMap.Builder<Integer, JSONObject> cmbld = ImmutableMap.builder();
cmbld.put(m_localHostId, m_acceptor.decorate(responseBody, Optional.<Boolean>empty()));
/*
* Loop over all the hosts and create a connection (except for the first entry, that is the leader)
* and publish the host id that was generated. This finishes creating the mesh
*/
JSONArray otherHosts = responseBody.getJSONArray(HOSTS);
int[] hostIds = new int[otherHosts.length()];
SocketChannel[] hostSockets = new SocketChannel[hostIds.length];
InetSocketAddress[] listeningAddresses = new InetSocketAddress[hostIds.length];
for (int ii = 0; ii < otherHosts.length(); ii++) {
JSONObject host = otherHosts.getJSONObject(ii);
String address = host.getString(ADDRESS);
int port = host.getInt(PORT);
final int hostId = host.getInt(HOST_ID);
LOG.info("Leader provided address " + address + ":" + port);
InetSocketAddress hostAddr = new InetSocketAddress(address, port);
if (ii == 0) {
//Leader already has a socket
hostIds[ii] = hostId;
listeningAddresses[ii] = hostAddr;
hostSockets[ii] = socket;
cmbld.put(ii, response.getLeaderInfo());
continue;
}
// connect to all the peer hosts (except leader) and advertise our existence
SocketChannel hostSocket = connectToHost(hostAddr);
JSONObject hostInfo = publishHostId(hostAddr, hostSocket, skews, activeVersions);
hostIds[ii] = hostId;
hostSockets[ii] = hostSocket;
listeningAddresses[ii] = hostAddr;
cmbld.put(ii, hostInfo);
}
/*
* The max difference of clock skew cannot exceed MAX_CLOCKSKEW, and the number of
* active versions in the cluster cannot be more than 2.
*/
checkClockSkew(skews);
checkActiveVersions(activeVersions, m_acceptor.getVersionChecker().getVersionString());
/*
* Notify the leader that we connected to the entire cluster, it will then go
* and queue a txn for our agreement site to join the cluster
*/
ByteBuffer joinCompleteBuffer = ByteBuffer.allocate(1);
while (joinCompleteBuffer.hasRemaining()) {
hostSockets[0].write(joinCompleteBuffer);
}
/*
* Let host messenger know about the connections.
* It will init the agreement site and then we are done.
*/
m_joinHandler.notifyOfHosts(m_localHostId, hostIds, hostSockets, listeningAddresses, cmbld.build());
} catch (ClosedByInterruptException e) {
//This is how shutdown is done
}
}
Aggregations