use of io.fabric8.kubernetes.api.model.Event in project fabric8 by jboss-fuse.
the class OpenwireProtocol method snoopConnectionParameters.
@Override
public void snoopConnectionParameters(final SocketWrapper socket, Buffer received, final Handler<ConnectionParameters> handler) {
OpenwireProtocolDecoder h = new OpenwireProtocolDecoder(this);
h.errorHandler(new Handler<String>() {
@Override
public void handle(String error) {
LOG.info("Openwire protocol decoding error: " + error);
socket.close();
}
});
h.codecHandler(new Handler<Command>() {
@Override
public void handle(Command event) {
if (event instanceof WireFormatInfo) {
WireFormatInfo info = (WireFormatInfo) event;
ConnectionParameters parameters = new ConnectionParameters();
try {
parameters.protocolVirtualHost = info.getHost();
} catch (IOException e) {
e.printStackTrace();
}
handler.handle(parameters);
} else {
LOG.info("Expected a WireFormatInfo frame");
socket.close();
}
}
});
socket.readStream().dataHandler(h);
h.handle(received);
}
use of io.fabric8.kubernetes.api.model.Event in project fabric8 by jboss-fuse.
the class DetectingGateway method handle.
public void handle(final SocketWrapper socket) {
try {
shutdownTracker.retain();
if (!socketsConnecting.add(socket)) {
throw new AssertionError("Socket existed in the socketsConnecting set");
}
} catch (Throwable e) {
LOG.debug("Could not accept connection from: " + socket.remoteAddress(), e);
socket.close();
// shutdownTracker.release();
return;
}
receivedConnectionAttempts.incrementAndGet();
if (connectionTimeout > 0) {
vertx.setTimer(connectionTimeout, new Handler<Long>() {
public void handle(Long timerID) {
if (socketsConnecting.contains(socket)) {
handleConnectFailure(socket, String.format("Gateway client '%s' protocol detection timeout.", socket.remoteAddress()));
}
}
});
}
ReadStream<ReadStream> readStream = socket.readStream();
readStream.exceptionHandler(new Handler<Throwable>() {
@Override
public void handle(Throwable e) {
handleConnectFailure(socket, String.format("Failed to route gateway client '%s' due to: %s", socket.remoteAddress(), e));
}
});
readStream.endHandler(new Handler<Void>() {
@Override
public void handle(Void event) {
handleConnectFailure(socket, String.format("Gateway client '%s' closed the connection before it could be routed.", socket.remoteAddress()));
}
});
readStream.dataHandler(new Handler<Buffer>() {
Buffer received = new Buffer();
{
LOG.debug("Inititalized new Handler[{}] for socket: {}", this, socket.remoteAddress());
}
@Override
public void handle(Buffer event) {
received.appendBuffer(event);
if (LOG.isTraceEnabled()) {
LOG.trace("Socket received following data: {}", event.copy().toString().replaceAll("\r", " "));
LOG.trace("Data handled by Handler {}", this.toString());
}
for (final Protocol protocol : protocols) {
if (protocol.matches(received)) {
if ("ssl".equals(protocol.getProtocolName())) {
LOG.info(String.format("SSL Connection from '%s'", socket.remoteAddress()));
String disabledCypherSuites = null;
String enabledCipherSuites = null;
if (sslConfig != null) {
disabledCypherSuites = sslConfig.getDisabledCypherSuites();
enabledCipherSuites = sslConfig.getEnabledCipherSuites();
}
if (sslContext == null) {
try {
if (sslConfig != null) {
sslContext = SSLContext.getInstance(sslConfig.getProtocol());
sslContext.init(sslConfig.getKeyManagers(), sslConfig.getTrustManagers(), null);
} else {
sslContext = SSLContext.getDefault();
}
} catch (Exception e) {
handleConnectFailure(socket, "Could initialize SSL: " + e);
return;
}
}
// lets wrap it up in a SslSocketWrapper.
SslSocketWrapper sslSocketWrapper = new SslSocketWrapper(socket);
sslSocketWrapper.putBackHeader(received);
sslSocketWrapper.initServer(sslContext, clientAuth, disabledCypherSuites, enabledCipherSuites);
// Undo initial connection accounting since we will be redoing @ the SSL level.
boolean removed = socketsConnecting.remove(socket);
assert removed;
receivedConnectionAttempts.decrementAndGet();
try {
DetectingGateway.this.handle(sslSocketWrapper);
} finally {
shutdownTracker.release();
}
return;
} else if ("http".equals(protocol.getProtocolName())) {
InetSocketAddress target = getHttpGateway();
if (target != null) {
try {
URI url = new URI("http://" + target.getHostString() + ":" + target.getPort());
LOG.info(String.format("Connecting '%s' to '%s:%d' using the http protocol", socket.remoteAddress(), url.getHost(), url.getPort()));
ConnectionParameters params = new ConnectionParameters();
params.protocol = "http";
createClient(params, socket, url, received);
return;
} catch (URISyntaxException e) {
handleConnectFailure(socket, "Could not build valid connect URI: " + e);
return;
}
} else {
handleConnectFailure(socket, "No http gateway available for the http protocol");
return;
}
} else {
protocol.snoopConnectionParameters(socket, received, new Handler<ConnectionParameters>() {
@Override
public void handle(ConnectionParameters connectionParameters) {
// this will install a new dataHandler on the socket.
if (connectionParameters.protocol == null)
connectionParameters.protocol = protocol.getProtocolName();
if (connectionParameters.protocolSchemes == null)
connectionParameters.protocolSchemes = protocol.getProtocolSchemes();
route(socket, connectionParameters, received);
}
});
return;
}
}
}
if (received.length() >= maxProtocolIdentificationLength) {
handleConnectFailure(socket, "Connection did not use one of the enabled protocols " + getProtocolNames());
}
}
});
}
use of io.fabric8.kubernetes.api.model.Event in project fabric8 by jboss-fuse.
the class AmqpProtocol method experimentalSnoopConnectionParameters.
public void experimentalSnoopConnectionParameters(final NetSocket socket, final Buffer received, final Handler<ConnectionParameters> handler) {
final AmqpProtocolDecoder h = new AmqpProtocolDecoder(this);
final ConnectionParameters parameters = new ConnectionParameters();
h.errorHandler(new Handler<String>() {
@Override
public void handle(String error) {
LOG.info("STOMP protocol decoding error: " + error);
socket.close();
}
});
h.codecHandler(new Handler<AmqpEvent>() {
EngineFactory engineFactory = new EngineFactoryImpl();
Transport protonTransport = engineFactory.createTransport();
Connection protonConnection = engineFactory.createConnection();
Sasl sasl;
@Override
public void handle(AmqpEvent event) {
switch(event.type) {
case HEADER:
AmqpHeader header = (AmqpHeader) event.decodedFrame;
switch(header.getProtocolId()) {
case 0:
// amqpTransport.sendToAmqp(new AmqpHeader());
break;
// nothing to do..
case 3:
// Client will be using SASL for auth..
sasl = protonTransport.sasl();
// sasl.setMechanisms(new String[] { "ANONYMOUS", "PLAIN" });
sasl.server();
break;
default:
}
processEvent(event);
// Les send back the AMQP response headers so that the client
// can send us the SASL init or AMQP open frames.
Buffer buffer = toBuffer(protonTransport.getOutputBuffer());
protonTransport.outputConsumed();
socket.write(buffer);
break;
default:
processEvent(event);
}
}
private void processEvent(AmqpEvent event) {
byte[] buffer = event.encodedFrame.getBytes();
int offset = 0;
int remaining = buffer.length;
while (remaining > 0) {
try {
int count = protonTransport.input(buffer, offset, remaining);
offset += count;
remaining -= count;
} catch (Throwable e) {
LOG.info("Could not decode AMQP frame: " + e, e);
socket.close();
return;
}
if (sasl != null) {
// TODO: add timeout in case the client is waiting for SASL negotiation
if (sasl.getRemoteMechanisms().length > 0) {
parameters.protocolVirtualHost = getHostname(sasl);
if ("PLAIN".equals(sasl.getRemoteMechanisms()[0])) {
byte[] data = new byte[sasl.pending()];
sasl.recv(data, 0, data.length);
Buffer[] parts = split(new Buffer(data), (byte) 0);
if (parts.length > 0) {
parameters.protocolUser = parts[0].toString();
}
// We are done!
handler.handle(parameters);
}
}
}
if (protonConnection.getLocalState() == EndpointState.UNINITIALIZED && protonConnection.getRemoteState() != EndpointState.UNINITIALIZED) {
// If we get here them the connection was not using SASL.. we can get the hostname
// info from the open frame.
parameters.protocolVirtualHost = protonConnection.getRemoteHostname();
// We are done!
handler.handle(parameters);
}
}
}
});
socket.dataHandler(h);
h.handle(received);
}
use of io.fabric8.kubernetes.api.model.Event in project fabric8 by jboss-fuse.
the class ServiceFactoryTest method testCallbackOnDisconnectCanClose.
@Test
public void testCallbackOnDisconnectCanClose() throws Exception {
curator.close();
LOG.info("....");
SocketProxy socketProxy = new SocketProxy(new URI("tcp://localhost:" + zkPort));
final CuratorFramework proxyCurator = CuratorFrameworkFactory.builder().connectString("localhost:" + socketProxy.getUrl().getPort()).sessionTimeoutMs(5000).connectionTimeoutMs(3000).retryPolicy(new RetryNTimes(10, 1000)).build();
proxyCurator.start();
proxyCurator.getZookeeperClient().blockUntilConnectedOrTimedOut();
LOG.info("curator is go: " + proxyCurator);
final String path = "/singletons/test/threads" + System.currentTimeMillis() + "**";
final ArrayList<Runnable> members = new ArrayList<Runnable>();
final int nThreads = 1;
final CountDownLatch gotDisconnectEvent = new CountDownLatch(1);
class GroupRunnable implements Runnable, GroupListener<NodeState> {
final int id;
private final BlockingQueue<Integer> jobQueue = new LinkedBlockingDeque<Integer>();
ZooKeeperGroup<NodeState> group;
NodeState nodeState;
public GroupRunnable(int id) {
this.id = id;
members.add(this);
nodeState = new NodeState("foo" + id);
}
@Override
public void run() {
group = new ZooKeeperGroup<NodeState>(proxyCurator, path, NodeState.class);
group.add(this);
LOG.info("run: Added: " + this);
try {
while (true) {
switch(jobQueue.take()) {
case 0:
LOG.info("run: close: " + this);
try {
group.close();
} catch (IOException ignored) {
}
return;
case 1:
LOG.info("run: start: " + this);
group.start();
group.update(nodeState);
break;
case 2:
LOG.info("run: update: " + this);
nodeState.setId(nodeState.getId() + id);
group.update(nodeState);
break;
}
}
} catch (InterruptedException exit) {
}
}
@Override
public void groupEvent(Group<NodeState> group, GroupEvent event) {
LOG.info("Got: event: " + event);
if (event.equals(GroupEvent.DISCONNECTED)) {
gotDisconnectEvent.countDown();
}
}
}
;
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nThreads; i++) {
executorService.execute(new GroupRunnable(i));
}
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
groupRunnable.jobQueue.offer(1);
// wait for registration
while (groupRunnable.group == null || groupRunnable.group.getId() == null) {
TimeUnit.MILLISECONDS.sleep(100);
}
}
boolean firsStartedIsMaster = ((GroupRunnable) members.get(0)).group.isMaster();
assertTrue("first started is master", firsStartedIsMaster);
LOG.info("got master...");
// lets see how long they take to notice a no responses to heart beats
socketProxy.pause();
// splash in an update
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
groupRunnable.jobQueue.offer(2);
}
boolean hasMaster = true;
while (hasMaster) {
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
hasMaster &= groupRunnable.group.isMaster();
}
if (hasMaster) {
LOG.info("Waiting for no master state on proxy pause");
TimeUnit.SECONDS.sleep(1);
}
}
try {
boolean gotDisconnect = gotDisconnectEvent.await(15, TimeUnit.SECONDS);
assertTrue("got disconnect event", gotDisconnect);
LOG.info("do close");
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
groupRunnable.jobQueue.offer(0);
}
executorService.shutdown();
// at a min when the session has expired
boolean allThreadComplete = executorService.awaitTermination(6, TimeUnit.SECONDS);
assertTrue("all threads complete", allThreadComplete);
} finally {
proxyCurator.close();
socketProxy.close();
}
}
use of io.fabric8.kubernetes.api.model.Event in project fabric8 by jboss-fuse.
the class ServiceFactoryTest method testThreadsOnTimeout.
@Test
public void testThreadsOnTimeout() throws Exception {
curator.close();
SocketProxy socketProxy = new SocketProxy(new URI("tcp://localhost:" + zkPort));
final CuratorFramework proxyCurator = CuratorFrameworkFactory.builder().connectString("localhost:" + socketProxy.getUrl().getPort()).sessionTimeoutMs(5000).connectionTimeoutMs(3000).retryPolicy(new RetryNTimes(10, 1000)).build();
proxyCurator.start();
proxyCurator.getZookeeperClient().blockUntilConnectedOrTimedOut();
LOG.info("curator is go: " + proxyCurator);
final String path = "/singletons/test/threads" + System.currentTimeMillis() + "**";
final ArrayList<Runnable> members = new ArrayList<Runnable>();
final int nThreads = 1;
class GroupRunnable implements Runnable, GroupListener<NodeState> {
final int id;
private final BlockingQueue<Integer> jobQueue = new LinkedBlockingDeque<Integer>();
ZooKeeperGroup<NodeState> group;
NodeState nodeState;
public GroupRunnable(int id) {
this.id = id;
members.add(this);
nodeState = new NodeState("foo" + id);
}
@Override
public void run() {
group = new ZooKeeperGroup<NodeState>(proxyCurator, path, NodeState.class);
group.add(this);
LOG.info("run: Added: " + this);
try {
while (true) {
switch(jobQueue.take()) {
case 0:
LOG.info("run: close: " + this);
try {
group.close();
} catch (IOException ignored) {
}
return;
case 1:
LOG.info("run: start: " + this);
group.start();
group.update(nodeState);
break;
case 2:
LOG.info("run: update: " + this);
nodeState.setId(nodeState.getId() + id);
group.update(nodeState);
break;
}
}
} catch (InterruptedException exit) {
}
}
@Override
public void groupEvent(Group<NodeState> group, GroupEvent event) {
}
}
;
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nThreads; i++) {
executorService.execute(new GroupRunnable(i));
}
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
groupRunnable.jobQueue.offer(1);
// wait for registration
while (groupRunnable.group == null || groupRunnable.group.getId() == null) {
TimeUnit.MILLISECONDS.sleep(100);
}
}
boolean firsStartedIsMaster = ((GroupRunnable) members.get(0)).group.isMaster();
assertTrue("first started is master", firsStartedIsMaster);
LOG.info("got master...");
// lets see how long they take to notice a no responses to heart beats
socketProxy.pause();
// splash in an update
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
groupRunnable.jobQueue.offer(2);
}
boolean hasMaster = true;
while (hasMaster) {
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
hasMaster &= groupRunnable.group.isMaster();
}
if (hasMaster) {
LOG.info("Waiting for no master state on proxy pause");
TimeUnit.SECONDS.sleep(1);
}
}
for (Runnable r : members) {
GroupRunnable groupRunnable = (GroupRunnable) r;
groupRunnable.jobQueue.offer(0);
}
executorService.shutdown();
// at a min when the session has expired
boolean allThreadComplete = executorService.awaitTermination(6, TimeUnit.SECONDS);
proxyCurator.close();
socketProxy.close();
assertTrue("all threads complete", allThreadComplete);
}
Aggregations