Max socket number reached and excpetion thrown
I am sending messages rapidly with the code below
private MsgResult send(Message msg) {
ZMQ.Socket client = MQSocketFactory.getMQSocket(serverEndpoint).createRequester();
try {
final byte[] DTO = Helper.serializeMessage(msg);
int retriesLeft = 1;
MsgResult msgResult = new MsgResult(MessageConstants.MESSAGE_FAIL);
while (retriesLeft > 0 && !Thread.currentThread().isInterrupted()) {
client.send(DTO, 0);
int expect_reply = 1;
while (expect_reply > 0) {
ZMQ.PollItem items[] = { new ZMQ.PollItem(client, Poller.POLLIN) };
int rc = ZMQ.poll(items, 3800);
if (rc == -1) break; // Interrupted
if (items[0].isReadable()) {
final byte[] reply = client.recv(0);
if (reply == null) break;
msgResult = new MsgResult(new String(reply));
if (msgResult.isSuccessful()) {
LOGGER.trace("Server replied OK. Result: [{}]", msgResult);
retriesLeft = 0;
expect_reply = 0;
} else LOGGER.error("Malformed reply from server: [{}]", msgResult);
} else if (--retriesLeft == 0) {
LOGGER.error("Server:[{}] seems to be offline, abandoning sending mt [{}]!", serverEndpoint, mt);
break;
} else {
LOGGER.warn("No response from server, retrying...");
client = MQSocketFactory.getMQSocket(serverEndpoint).resetRequester(client);
client.send(DTO, 0);
}
}
}
return mtResult;
} finally {
MQSocketFactory.getMQSocket(serverEndpoint).destroyRequester(client);
}
}
And the destroyRequester is this:
public void destroyRequester(ZMQ.Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
LOGGER.error("Error: {}", e.getMessage());
LOGGER.debug("Error: {}", e);
}
}
}
But from time to time (especially when the other end is down) I get EMFILE error which implies max sockets limit was reached. I am not sure why this happens though since I destroy every socket with socket.close() in the finally. Do you have any ideas? Am I doing something wrongly?
How "rapidly"? The socket.close() method is asynchronous. If you are creating and closing sockets very rapidly it's possible that many are not yet closed, and you'll run out of file descriptors.
rapidly would be 30 to 100 messages per second and each message opens a new socket, is sent and then the socket is closed as described in the code above. I don't know if this is supposed to be too much. I have noticed that this happens most of the times when the other end is offline thus I suppose it takes 3.8 seconds for it to close so they accumulate rapidly. But it has happened with the other end being up as well so the above theory does not explain everything.
Is there a good way to avoid this error? i.e. take into account the asynchronous nature for the socket.close() method?
Any news on this issue?
It seems that the "opening rapidly" sockets explanation is probably not correct. Because I just had this issue with a traffic of 8 Msg/Sec. It seems to me that somehow when I do the destroyRequester it does not actually close the socket and they are accumulated over time. Is the code I have posted above correct in terms of closing the sockets?
A fix on socket close has been merged. But the close request is still async opeation so rapid open/close would raise EMFILE eventually.
The fix is in 0.3.5? Because this is what I use
@menwn The fix is in v0.3.5
@trevorbernard I am using this one.
I am worried that this problem might not have to do with the fact that the release of sockets is asynchronous. Because zeroMQ is supposed to be able to handle a considerable amount of transactions per second and my experience indicates that it is not how rapidly the transactions take place and the sockets are released because I just had this issue with an average of 8 TPS.
My experience indicates that somehow sockets are accumulating, unreleased. Maybe the code I have above does not actually release the sockets somehow. Or maybe it does not release all sockets. Although I fail to see how this happens.
This is how I obtain the socket
private static final Map<String, MQSocket> store = new HashMap<String, MQSocket>();
public static MQSocket getMQSocket(String endpointName) {
synchronized (store) {
MQSocket result = store.get(endpointName);
if (result == null) {
result = new MQSocket(endpointName);
store.put(endpointName, result);
}
return result;
}
}
public static final class MQSocket {
private final String endpoint;
private final ZMQ.Context ctx;
private MQSocket(String endpointName) {
this.endpoint = endpointName;
this.ctx = ZMQ.context(1);
}
public ZMQ.Socket createRequester() {
ZMQ.Socket client = null;
try {
client = ctx.socket(ZMQ.REQ);
assert (client != null);
client.connect(endpoint);
} catch (Exception e) {
LOGGER.error("Error: {}", e.getMessage());
LOGGER.debug("Error: {}", e);
}
return client;
}
[...]
If the problem is not in my code then I think we should look into the release of sockets process.
@trevorbernard I am using this one.
I am worried that this problem might not have to do with the fact that the release of sockets is asynchronous. Because zeroMQ is supposed to be able to handle a considerable amount of transactions per second and my experience indicates that it is not how rapidly the transactions take place and the sockets are released because I just had this issue with an average of 8 TPS.
My experience indicates that somehow sockets are accumulating, unreleased. Maybe the code I have above does not actually release the sockets somehow. Or maybe it does not release all sockets. Although I fail to see how this happens.
This is how I obtain the socket
private static final Map<String, MQSocket> store = new HashMap<String, MQSocket>(); //I keep one context per endpoint
public static MQSocket getMQSocket(String endpointName) {
synchronized (store) {
MQSocket result = store.get(endpointName);
if (result == null) {
result = new MQSocket(endpointName);
store.put(endpointName, result);
}
return result;
}
}
public static final class MQSocket {
private final String endpoint;
private final ZMQ.Context ctx;
private MQSocket(String endpointName) {
this.endpoint = endpointName;
this.ctx = ZMQ.context(1);
}
public ZMQ.Socket createRequester() {
ZMQ.Socket client = null;
try {
client = ctx.socket(ZMQ.REQ);
assert (client != null);
client.connect(endpoint);
} catch (Exception e) {
LOGGER.error("Error: {}", e.getMessage());
LOGGER.debug("Error: {}", e);
}
return client;
}
[...]
If the problem is not in my code then I think we should look into the release of sockets process.
Few things I noticed glancing at the code:
I think you have a resource leak in your code. You only close the final socket, but you open several if retries are attempted. Unless you're closing the context somewhere else in that code, that would potentially close the others automatically. But assuming the context stays open for any period of time, you'll get your EMFILE error eventually due to resource leak.
To solve this, you should close your socket immediately when creating a new one for a re-try. That should a) solve the resource leak, and b) would be more correct behavior. Otherwise, you risk leaving queues open that could connect later and bombard the remote server with multiple duplicate messages.
However, it begs the question, why do retries at all? If ZeroMQ will automatically reconnect if the server comes back within your timeout period, I think you can eliminate the retries entirely, as you've established the server is not there if it does not respond. No?
Also, It seems an anti-pattern to open/close the socket for each send. You could possibly keep it around and re-use it.
Hi Stephen,
Thank you for your reply. About the resource leak. I thought I had this covered with the
client = MQSocketFactory.getMQSocket(serverEndpoint).resetRequester(client);
The resetRequester(client) is defined as
public ZMQ.Socket resetRequester(ZMQ.Socket socket) {
destroyRequester(socket); //Closes the socket
return createRequester();
}
Am I wrong? Now for the open/close socket for each send I implemented it from the zeroMQ guide where it is described as the Lazy Pirate Pattern (http://zguide.zeromq.org/php:chapter4#Client-Side-Reliability-Lazy-Pirate-Pattern)
"If you try to use a REQ socket in anything other than a strict send/receive fashion, you'll get an error (technically, the REQ socket implements a small finite-state machine to enforce the send/receive ping-pong, and so the error code is called "EFSM"). This is slightly annoying when we want to use REQ in a pirate pattern, because we may send several requests before getting a reply.
The pretty good brute force solution is to close and reopen the REQ socket after an error"
You are correct, it looks like you're closing the socket. But you're only posting snippets at a time, so I couldn't see the full context of the code. So that appears to be correct. Hard to tell 100% unless you post the entire context (maybe a github gist?). If so, I don't see any other resource leaks, so I'm at a loss for your core problem.
As to the Lazy Pirate, you are partially correct to my knowledge. You should definitely close the old socket and open a new one if a reply fails to come over within the desired timeout. You appear to have that piece correct. However, you are also opening a new socket for every invocation of your send() method. This (to me) would be something of an anti-pattern. You should only have to close the socket (Lazy Pirate) if you fail to get a reply. If everything is going well, the socket can be re-used indefinitely.
Make sense?
Yes you are correct I should have created a gist. Sorry about that. I do close all sockets because I did have resource leaks prior to fixing this. But this is not an issue any more.
You are probably right about the socket close and I will look into how to change to reuse the socket. Thanks!