Change license to Apache2 and reformat

This commit is contained in:
rbygrave committed 2012-09-15 00:00:08 +12:00
1 parent 96ce4c0ddf
commit 7aae897def
560 files changed
+73292 -85907

No files matched your search

@@ -1,76 +1,59 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This parses and dispatches a request to the appropriate handler.
* <p>
* Looks up the appropriate RequestHandler
* and then gets it to process the Client request.<P>
* </p>
* Note that this is a Runnable because it is assigned to the ThreadPool.
*/
class RequestProcessor implements Runnable {
private static final Logger logger = Logger.getLogger(RequestProcessor.class.getName());
private final Socket clientSocket;
private final SocketClusterBroadcast owner;
/**
* Create including the Listener (used to lookup the Request Handler) and
* the socket itself.
*/
public RequestProcessor(SocketClusterBroadcast owner, Socket clientSocket) {
this.clientSocket = clientSocket;
this.owner = owner;
}
/**
* This will parse out the command. Lookup the appropriate Handler and
* pass the information to the handler for processing.
* <P>Dev Note: the command parsing is processed here so that it is preformed
* by the assigned thread rather than the listeners thread.</P>
*/
public void run() {
try {
SocketConnection sc = new SocketConnection(clientSocket);
while(true){
if (owner.process(sc)) {
// got the offline message or timeout
break;
}
}
sc.disconnect();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, null, e);
}
}
};
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This parses and dispatches a request to the appropriate handler.
* <p>
* Looks up the appropriate RequestHandler
* and then gets it to process the Client request.<P>
* </p>
* Note that this is a Runnable because it is assigned to the ThreadPool.
*/
class RequestProcessor implements Runnable {
private static final Logger logger = Logger.getLogger(RequestProcessor.class.getName());
private final Socket clientSocket;
private final SocketClusterBroadcast owner;
/**
* Create including the Listener (used to lookup the Request Handler) and
* the socket itself.
*/
public RequestProcessor(SocketClusterBroadcast owner, Socket clientSocket) {
this.clientSocket = clientSocket;
this.owner = owner;
}
/**
* This will parse out the command. Lookup the appropriate Handler and
* pass the information to the handler for processing.
* <P>Dev Note: the command parsing is processed here so that it is preformed
* by the assigned thread rather than the listeners thread.</P>
*/
public void run() {
try {
SocketConnection sc = new SocketConnection(clientSocket);
while(true){
if (owner.process(sc)) {
// got the offline message or timeout
break;
}
}
sc.disconnect();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, null, e);
}
}
};
@@ -1,151 +1,134 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The client side of the socket clustering.
*/
class SocketClient {
private static final Logger logger = Logger.getLogger(SocketClient.class.getName());
private final InetSocketAddress address;
private final String hostPort;
private boolean online;
private Socket socket;
private OutputStream os;
private ObjectOutputStream oos;
/**
* Construct with an IP address and port.
*/
public SocketClient(InetSocketAddress address) {
this.address = address;
this.hostPort = address.getHostName()+":"+address.getPort();
}
public String getHostPort() {
return hostPort;
}
public int getPort() {
return address.getPort();
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) throws IOException {
if (online){
setOnline();
} else {
disconnect();
}
}
/**
* Set whether the client is thought to be online.
*/
private void setOnline() throws IOException {
connect();
this.online = true;
}
public void reconnect() throws IOException {
disconnect();
connect();
}
private void connect() throws IOException {
if (socket != null){
throw new IllegalStateException("Already got a socket connection?");
}
Socket s = new Socket();
s.setKeepAlive(true);
s.connect(address);
this.socket = s;
this.os = socket.getOutputStream();
}
public void disconnect() {
this.online = false;
if (socket != null){
try {
socket.close();
} catch (IOException e) {
String msg = "Error disconnecting from Cluster member "+hostPort;
logger.log(Level.INFO, msg, e);
}
os = null;
oos = null;
socket = null;
}
}
public boolean register(SocketClusterMessage registerMsg) {
try {
setOnline();
send(registerMsg);
return true;
} catch (IOException e) {
disconnect();
return false;
}
}
public boolean send(SocketClusterMessage msg) throws IOException {
if (online){
writeObject(msg);
return true;
} else {
return false;
}
}
private void writeObject(Object object) throws IOException {
if (oos == null){
this.oos = new ObjectOutputStream(os);
}
oos.writeObject(object);
oos.flush();
}
}
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The client side of the socket clustering.
*/
class SocketClient {
private static final Logger logger = Logger.getLogger(SocketClient.class.getName());
private final InetSocketAddress address;
private final String hostPort;
private boolean online;
private Socket socket;
private OutputStream os;
private ObjectOutputStream oos;
/**
* Construct with an IP address and port.
*/
public SocketClient(InetSocketAddress address) {
this.address = address;
this.hostPort = address.getHostName()+":"+address.getPort();
}
public String getHostPort() {
return hostPort;
}
public int getPort() {
return address.getPort();
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) throws IOException {
if (online){
setOnline();
} else {
disconnect();
}
}
/**
* Set whether the client is thought to be online.
*/
private void setOnline() throws IOException {
connect();
this.online = true;
}
public void reconnect() throws IOException {
disconnect();
connect();
}
private void connect() throws IOException {
if (socket != null){
throw new IllegalStateException("Already got a socket connection?");
}
Socket s = new Socket();
s.setKeepAlive(true);
s.connect(address);
this.socket = s;
this.os = socket.getOutputStream();
}
public void disconnect() {
this.online = false;
if (socket != null){
try {
socket.close();
} catch (IOException e) {
String msg = "Error disconnecting from Cluster member "+hostPort;
logger.log(Level.INFO, msg, e);
}
os = null;
oos = null;
socket = null;
}
}
public boolean register(SocketClusterMessage registerMsg) {
try {
setOnline();
send(registerMsg);
return true;
} catch (IOException e) {
disconnect();
return false;
}
}
public boolean send(SocketClusterMessage msg) throws IOException {
if (online){
writeObject(msg);
return true;
} else {
return false;
}
}
private void writeObject(Object object) throws IOException {
if (oos == null){
this.oos = new ObjectOutputStream(os);
}
oos.writeObject(object);
oos.flush();
}
}
@@ -1,265 +1,248 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.cluster.ClusterBroadcast;
import com.avaje.ebeaninternal.server.cluster.ClusterManager;
import com.avaje.ebeaninternal.server.cluster.DataHolder;
import com.avaje.ebeaninternal.server.cluster.SerialiseTransactionHelper;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.transaction.RemoteTransactionEvent;
/**
* Broadcast messages across the cluster using sockets.
*/
public class SocketClusterBroadcast implements ClusterBroadcast {
private static final Logger logger = Logger.getLogger(SocketClusterBroadcast.class.getName());
private final SocketClient local;
private final HashMap<String,SocketClient> clientMap;
private final SocketClusterListener listener;
private SocketClient[] members;
private ClusterManager clusterManager;
private final TxnSerialiseHelper txnSerialiseHelper = new TxnSerialiseHelper();
private final AtomicInteger txnOutgoing = new AtomicInteger();
private final AtomicInteger txnIncoming = new AtomicInteger();
public SocketClusterBroadcast( ){
String localHostPort = GlobalProperties.get("ebean.cluster.local", null);
String members = GlobalProperties.get("ebean.cluster.members", null);
logger.info("Clustering using Sockets local["+localHostPort+"] members["+members+"]");
this.local = new SocketClient(parseFullName(localHostPort));
this.clientMap = new HashMap<String, SocketClient>();
String[] memArray = StringHelper.delimitedToArray(members, ",", false);
for (int i = 0; i < memArray.length; i++) {
InetSocketAddress member = parseFullName(memArray[i]);
SocketClient client = new SocketClient(member);
if (!local.getHostPort().equalsIgnoreCase(client.getHostPort())) {
// don't add the local one ...
clientMap.put(client.getHostPort(), client);
}
}
this.members = clientMap.values().toArray(new SocketClient[clientMap.size()]);
this.listener = new SocketClusterListener(this, local.getPort());
}
/**
* Return the current status of this instance.
*/
public SocketClusterStatus getStatus() {
// count of online members
int currentGroupSize = 0;
for (int i = 0; i < members.length; i++) {
if (members[i].isOnline()) {
++currentGroupSize;
}
}
int txnIn = txnIncoming.get();
int txnOut = txnOutgoing.get();
return new SocketClusterStatus(currentGroupSize, txnIn, txnOut);
}
public void startup(ClusterManager clusterManager) {
this.clusterManager = clusterManager;
try {
listener.startListening();
register();
} catch (IOException e) {
throw new PersistenceException(e);
}
}
public void shutdown() {
deregister();
listener.shutdown();
}
/**
* Register with all the other members of the Cluster.
*/
private void register() {
SocketClusterMessage h = SocketClusterMessage.register(local.getHostPort(), true);
for (int i = 0; i < members.length; i++) {
boolean online = members[i].register(h);
String msg = "Cluster Member ["+members[i].getHostPort()+"] online["+online+"]";
logger.info(msg);
}
}
protected void setMemberOnline(String fullName, boolean online) throws IOException {
synchronized (clientMap) {
String msg = "Cluster Member ["+fullName+"] online["+online+"]";
logger.info(msg);
SocketClient member = clientMap.get(fullName);
member.setOnline(online);
}
}
private void send(SocketClient client, SocketClusterMessage msg) {
try {
// alternative would be to connect/disconnect here
// but prefer to use keepalive
client.send(msg);
} catch (Exception ex){
logger.log(Level.SEVERE, "Error sending message", ex);
try {
client.reconnect();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error trying to reconnect", ex);
}
}
}
/**
* Send the payload to all the members of the cluster.
*/
public void broadcast(RemoteTransactionEvent remoteTransEvent) {
try {
txnOutgoing.incrementAndGet();
DataHolder dataHolder = txnSerialiseHelper.createDataHolder(remoteTransEvent);
SocketClusterMessage msg = SocketClusterMessage.transEvent(dataHolder);
broadcast(msg);
} catch (Exception e){
String msg = "Error sending RemoteTransactionEvent "+remoteTransEvent+" to cluster members.";
logger.log(Level.SEVERE, msg, e);
}
}
protected void broadcast(SocketClusterMessage msg) {
for (int i = 0; i < members.length; i++) {
send(members[i], msg);
}
}
/**
* Leave the cluster.
*/
private void deregister() {
SocketClusterMessage h = SocketClusterMessage.register(local.getHostPort(), false);
broadcast(h);
for (int i = 0; i < members.length; i++) {
members[i].disconnect();
}
}
/**
* Process a Cluster message.
*/
protected boolean process(SocketConnection request) throws IOException, ClassNotFoundException {
try {
SocketClusterMessage h = (SocketClusterMessage)request.readObject();
if (h.isRegisterEvent()){
setMemberOnline(h.getRegisterHost(), h.isRegister());
} else {
txnIncoming.incrementAndGet();
DataHolder dataHolder = h.getDataHolder();
RemoteTransactionEvent transEvent = txnSerialiseHelper.read(dataHolder);
transEvent.run();
}
if (h.isRegisterEvent() && !h.isRegister()){
// instance shutting down
return true;
} else {
return false;
}
} catch (InterruptedIOException e) {
String msg = "Timeout waiting for message";
logger.log(Level.INFO, msg, e);
try {
request.disconnect();
} catch (IOException ex){
logger.log(Level.INFO, "Error disconnecting after timeout", ex);
}
return true;
}
}
/**
* Parse a host:port into a InetSocketAddress.
*/
private InetSocketAddress parseFullName(String hostAndPort) {
try {
hostAndPort = hostAndPort.trim();
int colonPos = hostAndPort.indexOf(":");
if (colonPos == -1) {
String msg = "No colon \":\" in "+hostAndPort;
throw new IllegalArgumentException(msg);
}
String host = hostAndPort.substring(0, colonPos);
String sPort = hostAndPort.substring(colonPos + 1, hostAndPort.length());
int port = Integer.parseInt(sPort);
return new InetSocketAddress(host, port);
} catch (Exception ex){
throw new RuntimeException("Error parsing ["+hostAndPort+"] for the form [host:port]", ex);
}
}
class TxnSerialiseHelper extends SerialiseTransactionHelper {
@Override
public SpiEbeanServer getEbeanServer(String serverName) {
return (SpiEbeanServer)clusterManager.getServer(serverName);
}
}
}
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.cluster.ClusterBroadcast;
import com.avaje.ebeaninternal.server.cluster.ClusterManager;
import com.avaje.ebeaninternal.server.cluster.DataHolder;
import com.avaje.ebeaninternal.server.cluster.SerialiseTransactionHelper;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.transaction.RemoteTransactionEvent;
/**
* Broadcast messages across the cluster using sockets.
*/
public class SocketClusterBroadcast implements ClusterBroadcast {
private static final Logger logger = Logger.getLogger(SocketClusterBroadcast.class.getName());
private final SocketClient local;
private final HashMap<String,SocketClient> clientMap;
private final SocketClusterListener listener;
private SocketClient[] members;
private ClusterManager clusterManager;
private final TxnSerialiseHelper txnSerialiseHelper = new TxnSerialiseHelper();
private final AtomicInteger txnOutgoing = new AtomicInteger();
private final AtomicInteger txnIncoming = new AtomicInteger();
public SocketClusterBroadcast( ){
String localHostPort = GlobalProperties.get("ebean.cluster.local", null);
String members = GlobalProperties.get("ebean.cluster.members", null);
logger.info("Clustering using Sockets local["+localHostPort+"] members["+members+"]");
this.local = new SocketClient(parseFullName(localHostPort));
this.clientMap = new HashMap<String, SocketClient>();
String[] memArray = StringHelper.delimitedToArray(members, ",", false);
for (int i = 0; i < memArray.length; i++) {
InetSocketAddress member = parseFullName(memArray[i]);
SocketClient client = new SocketClient(member);
if (!local.getHostPort().equalsIgnoreCase(client.getHostPort())) {
// don't add the local one ...
clientMap.put(client.getHostPort(), client);
}
}
this.members = clientMap.values().toArray(new SocketClient[clientMap.size()]);
this.listener = new SocketClusterListener(this, local.getPort());
}
/**
* Return the current status of this instance.
*/
public SocketClusterStatus getStatus() {
// count of online members
int currentGroupSize = 0;
for (int i = 0; i < members.length; i++) {
if (members[i].isOnline()) {
++currentGroupSize;
}
}
int txnIn = txnIncoming.get();
int txnOut = txnOutgoing.get();
return new SocketClusterStatus(currentGroupSize, txnIn, txnOut);
}
public void startup(ClusterManager clusterManager) {
this.clusterManager = clusterManager;
try {
listener.startListening();
register();
} catch (IOException e) {
throw new PersistenceException(e);
}
}
public void shutdown() {
deregister();
listener.shutdown();
}
/**
* Register with all the other members of the Cluster.
*/
private void register() {
SocketClusterMessage h = SocketClusterMessage.register(local.getHostPort(), true);
for (int i = 0; i < members.length; i++) {
boolean online = members[i].register(h);
String msg = "Cluster Member ["+members[i].getHostPort()+"] online["+online+"]";
logger.info(msg);
}
}
protected void setMemberOnline(String fullName, boolean online) throws IOException {
synchronized (clientMap) {
String msg = "Cluster Member ["+fullName+"] online["+online+"]";
logger.info(msg);
SocketClient member = clientMap.get(fullName);
member.setOnline(online);
}
}
private void send(SocketClient client, SocketClusterMessage msg) {
try {
// alternative would be to connect/disconnect here
// but prefer to use keepalive
client.send(msg);
} catch (Exception ex){
logger.log(Level.SEVERE, "Error sending message", ex);
try {
client.reconnect();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error trying to reconnect", ex);
}
}
}
/**
* Send the payload to all the members of the cluster.
*/
public void broadcast(RemoteTransactionEvent remoteTransEvent) {
try {
txnOutgoing.incrementAndGet();
DataHolder dataHolder = txnSerialiseHelper.createDataHolder(remoteTransEvent);
SocketClusterMessage msg = SocketClusterMessage.transEvent(dataHolder);
broadcast(msg);
} catch (Exception e){
String msg = "Error sending RemoteTransactionEvent "+remoteTransEvent+" to cluster members.";
logger.log(Level.SEVERE, msg, e);
}
}
protected void broadcast(SocketClusterMessage msg) {
for (int i = 0; i < members.length; i++) {
send(members[i], msg);
}
}
/**
* Leave the cluster.
*/
private void deregister() {
SocketClusterMessage h = SocketClusterMessage.register(local.getHostPort(), false);
broadcast(h);
for (int i = 0; i < members.length; i++) {
members[i].disconnect();
}
}
/**
* Process a Cluster message.
*/
protected boolean process(SocketConnection request) throws IOException, ClassNotFoundException {
try {
SocketClusterMessage h = (SocketClusterMessage)request.readObject();
if (h.isRegisterEvent()){
setMemberOnline(h.getRegisterHost(), h.isRegister());
} else {
txnIncoming.incrementAndGet();
DataHolder dataHolder = h.getDataHolder();
RemoteTransactionEvent transEvent = txnSerialiseHelper.read(dataHolder);
transEvent.run();
}
if (h.isRegisterEvent() && !h.isRegister()){
// instance shutting down
return true;
} else {
return false;
}
} catch (InterruptedIOException e) {
String msg = "Timeout waiting for message";
logger.log(Level.INFO, msg, e);
try {
request.disconnect();
} catch (IOException ex){
logger.log(Level.INFO, "Error disconnecting after timeout", ex);
}
return true;
}
}
/**
* Parse a host:port into a InetSocketAddress.
*/
private InetSocketAddress parseFullName(String hostAndPort) {
try {
hostAndPort = hostAndPort.trim();
int colonPos = hostAndPort.indexOf(":");
if (colonPos == -1) {
String msg = "No colon \":\" in "+hostAndPort;
throw new IllegalArgumentException(msg);
}
String host = hostAndPort.substring(0, colonPos);
String sPort = hostAndPort.substring(colonPos + 1, hostAndPort.length());
int port = Integer.parseInt(sPort);
return new InetSocketAddress(host, port);
} catch (Exception ex){
throw new RuntimeException("Error parsing ["+hostAndPort+"] for the form [host:port]", ex);
}
}
class TxnSerialiseHelper extends SerialiseTransactionHelper {
@Override
public SpiEbeanServer getEbeanServer(String serverName) {
return (SpiEbeanServer)clusterManager.getServer(serverName);
}
}
}
@@ -1,181 +1,164 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPool;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPoolManager;
/**
* Serverside multithreaded socket listener. Accepts connections and dispatches
* them to an appropriate handler.
* <p>
* This is designed as a single port listener, where part of the connection
* protocol determines which service the client is requesting (rather than a
* port per service).
* </p>
* <p>
* It has its own daemon background thread that handles the accept() loop on the
* ServerSocket.
* </p>
*/
class SocketClusterListener implements Runnable {
private static final Logger logger = Logger.getLogger(SocketClusterListener.class.getName());
/**
* The port the SocketListener uses.
*/
private final int port;
/**
* The length of the socket accept timeout.
*/
private final int listenTimeout = 60000;
/**
* The server socket used to listen for requests.
*/
private final ServerSocket serverListenSocket;
/**
* The listening thread.
*/
private final Thread listenerThread;
/**
* The pool of threads that actually do the parsing execution of requests.
*/
private final ThreadPool threadPool;
private final SocketClusterBroadcast owner;
/**
* shutting down flag.
*/
boolean doingShutdown;
/**
* Whether the listening thread is busy assigning a request to a thread.
*/
boolean isActive;
/**
* Construct with a given thread pool name.
*/
public SocketClusterListener(SocketClusterBroadcast owner, int port) {
this.owner = owner;
this.threadPool = ThreadPoolManager.getThreadPool("EbeanClusterMember");
this.port = port;
try {
this.serverListenSocket = new ServerSocket(port);
this.serverListenSocket.setSoTimeout(listenTimeout);
this.listenerThread = new Thread(this, "EbeanClusterListener");
} catch (IOException e){
String msg = "Error starting cluster socket listener on port "+port;
throw new RuntimeException(msg,e);
}
}
/**
* Returns the port the listener is using.
*/
public int getPort() {
return port;
}
/**
* Start listening for requests.
*/
public void startListening() throws IOException {
this.listenerThread.setDaemon(true);
this.listenerThread.start();
}
/**
* Shutdown this listener.
*/
public void shutdown() {
doingShutdown = true;
try {
if (isActive) {
synchronized (listenerThread) {
try {
listenerThread.wait(1000);
} catch (InterruptedException e) {
// OK to ignore as expected to Interrupt for shutdown.
;
}
}
}
listenerThread.interrupt();
serverListenSocket.close();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
/**
* This is a runnable and so this must be public. Don't call this externally
* but rather call the startListening() method.
*/
public void run() {
// run in loop until doingShutdown is true...
while (!doingShutdown) {
try {
synchronized (listenerThread) {
Socket clientSocket = serverListenSocket.accept();
isActive = true;
Runnable request = new RequestProcessor(owner, clientSocket);
threadPool.assign(request, true);
isActive = false;
}
} catch (SocketException e) {
if (doingShutdown) {
String msg = "doingShutdown and accept threw:"+ e.getMessage();
logger.info(msg);
} else {
logger.log(Level.SEVERE, null, e);
}
} catch (InterruptedIOException e) {
// this will happen when the server is very quiet.
// that is, no requests
logger.fine("Possibly expected due to accept timeout?" + e.getMessage());
} catch (IOException e) {
// log it and continue in the loop...
logger.log(Level.SEVERE, null, e);
}
}
}
}
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPool;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPoolManager;
/**
* Serverside multithreaded socket listener. Accepts connections and dispatches
* them to an appropriate handler.
* <p>
* This is designed as a single port listener, where part of the connection
* protocol determines which service the client is requesting (rather than a
* port per service).
* </p>
* <p>
* It has its own daemon background thread that handles the accept() loop on the
* ServerSocket.
* </p>
*/
class SocketClusterListener implements Runnable {
private static final Logger logger = Logger.getLogger(SocketClusterListener.class.getName());
/**
* The port the SocketListener uses.
*/
private final int port;
/**
* The length of the socket accept timeout.
*/
private final int listenTimeout = 60000;
/**
* The server socket used to listen for requests.
*/
private final ServerSocket serverListenSocket;
/**
* The listening thread.
*/
private final Thread listenerThread;
/**
* The pool of threads that actually do the parsing execution of requests.
*/
private final ThreadPool threadPool;
private final SocketClusterBroadcast owner;
/**
* shutting down flag.
*/
boolean doingShutdown;
/**
* Whether the listening thread is busy assigning a request to a thread.
*/
boolean isActive;
/**
* Construct with a given thread pool name.
*/
public SocketClusterListener(SocketClusterBroadcast owner, int port) {
this.owner = owner;
this.threadPool = ThreadPoolManager.getThreadPool("EbeanClusterMember");
this.port = port;
try {
this.serverListenSocket = new ServerSocket(port);
this.serverListenSocket.setSoTimeout(listenTimeout);
this.listenerThread = new Thread(this, "EbeanClusterListener");
} catch (IOException e){
String msg = "Error starting cluster socket listener on port "+port;
throw new RuntimeException(msg,e);
}
}
/**
* Returns the port the listener is using.
*/
public int getPort() {
return port;
}
/**
* Start listening for requests.
*/
public void startListening() throws IOException {
this.listenerThread.setDaemon(true);
this.listenerThread.start();
}
/**
* Shutdown this listener.
*/
public void shutdown() {
doingShutdown = true;
try {
if (isActive) {
synchronized (listenerThread) {
try {
listenerThread.wait(1000);
} catch (InterruptedException e) {
// OK to ignore as expected to Interrupt for shutdown.
;
}
}
}
listenerThread.interrupt();
serverListenSocket.close();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
/**
* This is a runnable and so this must be public. Don't call this externally
* but rather call the startListening() method.
*/
public void run() {
// run in loop until doingShutdown is true...
while (!doingShutdown) {
try {
synchronized (listenerThread) {
Socket clientSocket = serverListenSocket.accept();
isActive = true;
Runnable request = new RequestProcessor(owner, clientSocket);
threadPool.assign(request, true);
isActive = false;
}
} catch (SocketException e) {
if (doingShutdown) {
String msg = "doingShutdown and accept threw:"+ e.getMessage();
logger.info(msg);
} else {
logger.log(Level.SEVERE, null, e);
}
} catch (InterruptedIOException e) {
// this will happen when the server is very quiet.
// that is, no requests
logger.fine("Possibly expected due to accept timeout?" + e.getMessage());
} catch (IOException e) {
// log it and continue in the loop...
logger.log(Level.SEVERE, null, e);
}
}
}
}
@@ -1,95 +1,78 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.Serializable;
import com.avaje.ebeaninternal.server.cluster.DataHolder;
import com.avaje.ebeaninternal.server.cluster.Packet;
/**
* The messages broadcast around the cluster.
*/
public class SocketClusterMessage implements Serializable {
private static final long serialVersionUID = 2993350408394934473L;
private final String registerHost;
private final boolean register;
private final DataHolder dataHolder;
public static SocketClusterMessage register(String registerHost, boolean register){
return new SocketClusterMessage(registerHost, register);
}
public static SocketClusterMessage transEvent(DataHolder transEvent){
return new SocketClusterMessage(transEvent);
}
public static SocketClusterMessage packet(Packet packet){
DataHolder d = new DataHolder(packet.getBytes());
return new SocketClusterMessage(d);
}
/**
* Used to construct a Child AttributeMap.
*/
private SocketClusterMessage(String registerHost, boolean register) {
this.registerHost = registerHost;
this.register = register;
this.dataHolder = null;
}
private SocketClusterMessage(DataHolder dataHolder) {
this.dataHolder = dataHolder;
this.registerHost = null;
this.register = false;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (registerHost != null){
sb.append("register ");
sb.append(register);
sb.append(" ");
sb.append(registerHost);
} else {
sb.append("transEvent ");
}
return sb.toString();
}
public boolean isRegisterEvent() {
return registerHost != null;
}
public String getRegisterHost() {
return registerHost;
}
public boolean isRegister() {
return register;
}
public DataHolder getDataHolder() {
return dataHolder;
}
}
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.Serializable;
import com.avaje.ebeaninternal.server.cluster.DataHolder;
import com.avaje.ebeaninternal.server.cluster.Packet;
/**
* The messages broadcast around the cluster.
*/
public class SocketClusterMessage implements Serializable {
private static final long serialVersionUID = 2993350408394934473L;
private final String registerHost;
private final boolean register;
private final DataHolder dataHolder;
public static SocketClusterMessage register(String registerHost, boolean register){
return new SocketClusterMessage(registerHost, register);
}
public static SocketClusterMessage transEvent(DataHolder transEvent){
return new SocketClusterMessage(transEvent);
}
public static SocketClusterMessage packet(Packet packet){
DataHolder d = new DataHolder(packet.getBytes());
return new SocketClusterMessage(d);
}
/**
* Used to construct a Child AttributeMap.
*/
private SocketClusterMessage(String registerHost, boolean register) {
this.registerHost = registerHost;
this.register = register;
this.dataHolder = null;
}
private SocketClusterMessage(DataHolder dataHolder) {
this.dataHolder = dataHolder;
this.registerHost = null;
this.register = false;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (registerHost != null){
sb.append("register ");
sb.append(register);
sb.append(" ");
sb.append(registerHost);
} else {
sb.append("transEvent ");
}
return sb.toString();
}
public boolean isRegisterEvent() {
return registerHost != null;
}
public String getRegisterHost() {
return registerHost;
}
public boolean isRegister() {
return register;
}
public DataHolder getDataHolder() {
return dataHolder;
}
}
@@ -1,60 +1,41 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
/**
* The current state of this cluster member.
*
* @author rbygrave
*/
public class SocketClusterStatus {
private final int currentGroupSize;
private final int txnIncoming;
private final int txtOutgoing;
public SocketClusterStatus(int currentGroupSize, int txnIncoming, int txnOutgoing) {
this.currentGroupSize = currentGroupSize;
this.txnIncoming = txnIncoming;
this.txtOutgoing = txnOutgoing;
}
/**
* Return the number of members of the cluster currently online.
*/
public int getCurrentGroupSize() {
return currentGroupSize;
}
/**
* Return the number of Remote transactions received.
*/
public int getTxnIncoming() {
return txnIncoming;
}
/**
* Return the number of transactions sent to the cluster.
*/
public int getTxtOutgoing() {
return txtOutgoing;
}
}
package com.avaje.ebeaninternal.server.cluster.socket;
/**
* The current state of this cluster member.
*
* @author rbygrave
*/
public class SocketClusterStatus {
private final int currentGroupSize;
private final int txnIncoming;
private final int txtOutgoing;
public SocketClusterStatus(int currentGroupSize, int txnIncoming, int txnOutgoing) {
this.currentGroupSize = currentGroupSize;
this.txnIncoming = txnIncoming;
this.txtOutgoing = txnOutgoing;
}
/**
* Return the number of members of the cluster currently online.
*/
public int getCurrentGroupSize() {
return currentGroupSize;
}
/**
* Return the number of Remote transactions received.
*/
public int getTxnIncoming() {
return txnIncoming;
}
/**
* Return the number of transactions sent to the cluster.
*/
public int getTxtOutgoing() {
return txtOutgoing;
}
}
@@ -1,146 +1,129 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* The client side of a TCP Sockect connection.
*/
class SocketConnection {
/**
* The object underlying objectOutputStream.
*/
ObjectOutputStream oos;
/**
* The underlying ObjectInputStream.
*/
ObjectInputStream ois;
/**
* The underlying inputStream.
*/
InputStream is;
/**
* The underlying outputStream.
*/
OutputStream os;
/**
* The underlying socket.
*/
Socket socket;
/**
* Create for a given Socket.
*/
public SocketConnection(Socket socket) throws IOException {
this.is = socket.getInputStream();
this.os = socket.getOutputStream();
this.socket = socket;
}
/**
* Disconnect from the server.
*/
public void disconnect() throws IOException {
os.flush();
socket.close();
}
/**
* Flush the outputStream.
*/
public void flush() throws IOException {
os.flush();
}
/**
* Read an object from the object input stream.
*/
public Object readObject() throws IOException, ClassNotFoundException {
return getObjectInputStream().readObject();
}
/**
* Write an object to the object output stream.
*/
public ObjectOutputStream writeObject(Object object) throws IOException {
ObjectOutputStream oos = getObjectOutputStream();
oos.writeObject(object);
return oos;
}
/**
* Get the object output stream.
*/
public ObjectOutputStream getObjectOutputStream() throws IOException {
if (oos == null){
oos = new ObjectOutputStream(os);
}
return oos;
}
/**
* Get the object input stream.
*/
public ObjectInputStream getObjectInputStream() throws IOException {
if (ois == null){
ois = new ObjectInputStream(is);
}
return ois;
}
/**
* Set the ObjectInputStream to use.
*/
public void setObjectInputStream(ObjectInputStream ois) {
this.ois = ois;
}
/**
* Set the ObjectOutputStream to use.
*/
public void setObjectOutputStream(ObjectOutputStream oos) {
this.oos = oos;
}
/**
* Return the underlying input stream.
*/
public InputStream getInputStream() throws IOException {
return is;
}
/**
* Return the underlying output stream.
*/
public OutputStream getOutputStream() throws IOException {
return os;
}
}
package com.avaje.ebeaninternal.server.cluster.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* The client side of a TCP Sockect connection.
*/
class SocketConnection {
/**
* The object underlying objectOutputStream.
*/
ObjectOutputStream oos;
/**
* The underlying ObjectInputStream.
*/
ObjectInputStream ois;
/**
* The underlying inputStream.
*/
InputStream is;
/**
* The underlying outputStream.
*/
OutputStream os;
/**
* The underlying socket.
*/
Socket socket;
/**
* Create for a given Socket.
*/
public SocketConnection(Socket socket) throws IOException {
this.is = socket.getInputStream();
this.os = socket.getOutputStream();
this.socket = socket;
}
/**
* Disconnect from the server.
*/
public void disconnect() throws IOException {
os.flush();
socket.close();
}
/**
* Flush the outputStream.
*/
public void flush() throws IOException {
os.flush();
}
/**
* Read an object from the object input stream.
*/
public Object readObject() throws IOException, ClassNotFoundException {
return getObjectInputStream().readObject();
}
/**
* Write an object to the object output stream.
*/
public ObjectOutputStream writeObject(Object object) throws IOException {
ObjectOutputStream oos = getObjectOutputStream();
oos.writeObject(object);
return oos;
}
/**
* Get the object output stream.
*/
public ObjectOutputStream getObjectOutputStream() throws IOException {
if (oos == null){
oos = new ObjectOutputStream(os);
}
return oos;
}
/**
* Get the object input stream.
*/
public ObjectInputStream getObjectInputStream() throws IOException {
if (ois == null){
ois = new ObjectInputStream(is);
}
return ois;
}
/**
* Set the ObjectInputStream to use.
*/
public void setObjectInputStream(ObjectInputStream ois) {
this.ois = ois;
}
/**
* Set the ObjectOutputStream to use.
*/
public void setObjectOutputStream(ObjectOutputStream oos) {
this.oos = oos;
}
/**
* Return the underlying input stream.
*/
public InputStream getInputStream() throws IOException {
return is;
}
/**
* Return the underlying output stream.
*/
public OutputStream getOutputStream() throws IOException {
return os;
}
}