Sunday, January 19, 2014

Understanding socket bind failures on WebSphere Application Server

If you are familiar with WebSphere Application Server, then you probably have already noticed that sometimes WebSphere seems to have problems reopening TCP ports after a restart. When this occurs, the following kind of error message is logged repeatedly:

TCPC0003E: TCP Channel TCP_2 initialization failed. The socket bind failed for host * and port 9080. The port may already be in use.

Eventually WebSphere will succeed in binding to the port, as indicated by the following message:

TCPC0001I: TCP Channel TCP_2 is listening on host * (IPv6) port 9080.

IBM recently published a technote about this problem. It concludes by claiming that there is no solution for this limitation and [WebSphere] is working as designed. That statement however misses some key points and is actually not quite accurate.

First of all, it is important to understand why the issue occurs. The problem is that on some of the TCP sockets it attempts to put into listen mode, WebSphere doesn't set the SO_REUSEADDR socket option. On Linux you can check that using the tool I presented in a previous blog post. You will see that the SO_REUSEADDR option is set on the sockets used by IIOP (BOOTSTRAP_ADDRESS and ORB_LISTENER_ADDRESS) and the SOAP JMX connector (SOAP_CONNECTOR_ADDRESS), but not on the sockets used by the Web container (WC_defaulthost, WC_defaulthost_secure, WC_adminhost and WC_adminhost_secure), the SIB service (SIB_ENDPOINT_ADDRESS and SIB_ENDPOINT_SECURE_ADDRESS) and the core group service (DCS_UNICAST_ADDRESS).

The problem with not setting SO_REUSEADDR is that the bind to a port will fail as long as there are TCP connections in state TIME_WAIT on that port. A connection will enter this state if the connection termination is initiated by the local end. E.g. when WebSphere decides to close an idle HTTP connection, then that connection will end up in state TIME_WAIT and prevent WebSphere from reopening the HTTP port after a restart. As can be seen in the TCP state diagram, a connection can only leave the TIME_WAIT state after the corresponding timeout is reached. At this point the connection transitions to the CLOSED state and the system discards all information about the connection. That is the reason why after several attempts, WebSphere eventually succeeds in binding to the port. It is also the reason why IBM's technote suggests modifying the timeout value.

More background on the TIME_WAIT state and the SO_REUSEADDR option can be found in section 18.6, "TCP State Transition Diagram" of W. Richard Stevens' classic textbook "TCP/IP Illustrated, Vol. 1":

The TIME_WAIT state is also called the 2MSL wait state. Every implementation must choose a value for the maximum segment lifetime (MSL). It is the maximum amount of time any segment can exist in the network before being discarded. [...]

Given the MSL value for an implementation, the rule is: when TCP performs an active close, and sends the final ACK, that connection must stay in the TIME_WAIT state for twice the MSL. This lets TCP resend the final ACK in case this ACK is lost (in which case the other end will time out and retransmit its final FIN).

Another effect of this 2MSL wait is that while the TCP connection is in the 2MSL wait, the socket pair defining that connection (client IP address, client port number, server IP address, and server port number) cannot be reused. That connection can only be reused when the 2MSL wait is over.

Unfortunately most implementations (i.e., the Berkeley-derived ones) impose a more stringent constraint. By default a local port number cannot be reused while that port number is the local port number of a socket pair that is in the 2MSL wait. [...]

Some implementations and APIs provide a way to bypass this restriction. With the sockets API, the SO_REUSEADDR socket option can be specified. It lets the caller assign itself a local port number that's in the 2MSL wait, but we'll see that the rules of TCP still prevent this port number from being part of a connection that is in the 2MSL wait.

The question is now why WebSphere doesn't use SO_REUSEADDR. The technote suggest that this is "by design", but fails to explain the rationale behind that "design". In addition, the quote from Stevens' book clearly shows that setting SO_REUSEADDR does no harm, and it is what most other server processes do.

There is another interesting aspect. I mentioned earlier that the problem only affects some ports opened by WebSphere, in particular the ones used by the Web container, the SIB service and the core group services. Interestingly, these ports are all managed by the WebSphere channel framework. They can easily be identified by looking at the "Ports" page for the server in the admin console:

Ports that have a link "View associated transports" are managed by the channel framework and don't use SO_REUSEADDR (Note that this suggests that the problem also exists for the ports used by the SIP service not considered earlier).

It turns out that the channel framework actually supports a custom property soReuseAddr that can be used to specify the value of the SO_REUSEADDR option. The corresponding documentation in the infocenter is interesting because it explicitly presents that custom property as a solution for the bind problem, contradicting the statement made in the technote that there is no solution:

Use the soReuseAddr custom property to control bind behavior. When the WebSphere Application Server is restarted, if the inbound TCP channels have problems trying to bind the listening socket, errors are printed into the SystemOut file until either the bind is successful or the number of allowed bind attempts has been passed. This custom property helps to avoid repeated error messages during the bind process.

For inbound TCP channel binding environments, you can avoid the repeated error messages by using the soReuseAddr custom property to affect TCP inbound channel processing. When soReuseAddr is set to 1, the TCP channel is forced to try each bind attempt with the re-use option set to true on the socket. The restart of the WebSphere Application Server processes first binding attempt, despite those sockets in TIME_WAIT state.

By setting the soReuseAddr property to 1 on all TCP inbound channels, it is indeed possible to avoid the TCPC0003E error entirely. To configure that property on a given port using the admin console, start from the corresponding "View associated transports" link and look for "TCP inbound channel". If you prefer to use admin scripting, write a script that locates all configuration objects of type TCPInboundChannel and adds the soReuseAddr property to these objects.

This is still not the complete story though. IBM's technote makes the following statement about the environments in which the problem occurs:

This problem may occur on Red Hat Enterprise Linux Server Release 5.9 with WebSphere Application Server versions -

Obviously the problem is not specific to a particular Linux distribution or version, but that is not the point here. What is more interesting is the range of WebSphere versions. The technote doesn't make it clear whether the problem only exists in WAS versions up to or whether was simply the current WAS version when the technote was written. It turns out that it is actually the former: in WAS the behavior is indeed no longer the same. Now all listening sockets are created with the SO_REUSEADDR option set by default, and the problem no longer exists.

This would suggest that IBM simply changed the default value of the soReuseAddr custom property to 1. However, a simple test with soReuseAddr=0 shows that WebSphere actually completely ignores the property and always enables SO_REUSEADDR, although the current version of the corresponding infocenter page still mentions the property and specifies that its default value is 0.

Saturday, January 18, 2014

How to suspend HTTP traffic to a WebSphere Application Server

One of the annoying things with the WebSphere plug-in for IBM HTTP Server is that there is no straightforward way to suspend traffic to a given application server. The problem is that the plug-in is not aware of the runtime weights of the members in a WebSphere cluster. The only way to suspend HTTP traffic to a given server is to set the configured weight of the cluster member to zero and then to regenerate and propagate the plug-in configuration file. The plug-in will automatically reread that file and stop sending HTTP requests to the server. Alternatively, one can also edit the plugin-cfg.xml file manually to temporarily set the LoadBalanceWeight to zero.

Obviously this method is cumbersome, especially compared to how this kind of operation is done on other load balancers. On the other hand, one of the advantages of the WebSphere plug-in is that it able to detect a stopped member and fail over the connections without loosing requests: as soon as it detects that the HTTP port on the WebSphere server is closed, it will redirect requests (including the request that caused the attempt to establish the connection to the application server) to other cluster members. Therefore another approach would be to instruct the application server to (temporarily) close its HTTP port(s) in order to force the WebSphere plug-in to route requests to other members.

It turns out that this is indeed possible. Each application server has an MBean of type WebContainer with operations stopTransports and startTransports. The first operation stops all HTTP transports and closes the corresponding ports, i.e. WC_defaulthost and WC_defaulthost_secure (as well as WC_adminhost and WC_adminhost_secure on stand-alone servers and deployment managers). The second operation restores normal operation.

As noted in PK96239, the WebContainer MBean was deprecated in WAS 6.1 and has been replaced by the TransportChannelService MBean. However, the latter is much more difficult to use and as of WAS 8.5.5, the WebContainer MBean is still supported. Therefore using the WebContainer MBean remains the preferred method to do this.

It should also be noted that using the stopTransports to suspend HTTP traffic to a WebSphere server may have some drawbacks in certain situations. The most important one is that since the HTTP ports are closed, it is no longer possible to send any kind of HTTP request to the server. In particular it is no longer possible to send test requests directly to the server. One should also be careful if there are applications deployed on the server that may send HTTP requests to the server itself (via localhost) in response to requests received via protocols other than HTTP, such as IIOP (remote EJB calls) or JMS.

Thursday, January 9, 2014

Quote of the day

Option three is Assad wins. And I must tell you at the moment, as ugly as it sounds, I'm kind of trending toward option three as the best out of three very, very ugly possible outcomes.

Michael Hayden, former head of the CIA

Wednesday, January 1, 2014

Graphic of the day

When a picture is worth a thousand words...

Source: (German).

How TCP backlog works in Linux

When an application puts a socket into LISTEN state using the listen syscall, it needs to specify a backlog for that socket. The backlog is usually described as the limit for the queue of incoming connections.

Because of the 3-way handshake used by TCP, an incoming connection goes through an intermediate state SYN RECEIVED before it reaches the ESTABLISHED state and can be returned by the accept syscall to the application (see the TCP state diagram). This means that a TCP/IP stack has two options to implement the backlog queue for a socket in LISTEN state:

  1. The implementation uses a single queue, the size of which is determined by the backlog argument of the listen syscall. When a SYN packet is received, it sends back a SYN/ACK packet and adds the connection to the queue. When the corresponding ACK is received, the connection changes its state to ESTABLISHED and becomes eligible for handover to the application. This means that the queue can contain connections in two different state: SYN RECEIVED and ESTABLISHED. Only connections in the latter state can be returned to the application by the accept syscall.
  2. The implementation uses two queues, a SYN queue (or incomplete connection queue) and an accept queue (or complete connection queue). Connections in state SYN RECEIVED are added to the SYN queue and later moved to the accept queue when their state changes to ESTABLISHED, i.e. when the ACK packet in the 3-way handshake is received. As the name implies, the accept call is then implemented simply to consume connections from the accept queue. In this case, the backlog argument of the listen syscall determines the size of the accept queue.

Historically, BSD derived TCP implementations use the first approach. That choice implies that when the maximum backlog is reached, the system will no longer send back SYN/ACK packets in response to SYN packets. Usually the TCP implementation will simply drop the SYN packet (instead of responding with a RST packet) so that the client will retry. This is what is described in section 14.5, listen Backlog Queue in W. Richard Stevens' classic textbook TCP/IP Illustrated, Volume 3.

Note that Stevens actually explains that the BSD implementation does use two separate queues, but they behave as a single queue with a fixed maximum size determined by (but not necessary exactly equal to) the backlog argument, i.e. BSD logically behaves as described in option 1:

The queue limit applies to the sum of [...] the number of entries on the incomplete connection queue [...] and [...] the number of entries on the completed connection queue [...].

On Linux, things are different, as mentioned in the man page of the listen syscall:

The behavior of the backlog argument on TCP sockets changed with Linux 2.2. Now it specifies the queue length for completely established sockets waiting to be accepted, instead of the number of incomplete connection requests. The maximum length of the queue for incomplete sockets can be set using /proc/sys/net/ipv4/tcp_max_syn_backlog.

This means that current Linux versions use the second option with two distinct queues: a SYN queue with a size specified by a system wide setting and an accept queue with a size specified by the application.

The interesting question is now how such an implementation behaves if the accept queue is full and a connection needs to be moved from the SYN queue to the accept queue, i.e. when the ACK packet of the 3-way handshake is received. This case is handled by the tcp_check_req function in net/ipv4/tcp_minisocks.c. The relevant code reads:

        child = inet_csk(sk)->icsk_af_ops->syn_recv_sock(sk, skb, req, NULL);
        if (child == NULL)
                goto listen_overflow;

For IPv4, the first line of code will actually call tcp_v4_syn_recv_sock in net/ipv4/tcp_ipv4.c, which contains the following code:

        if (sk_acceptq_is_full(sk))
                goto exit_overflow;

We see here the check for the accept queue. The code after the exit_overflow label will perform some cleanup, update the ListenOverflows and ListenDrops statistics in /proc/net/netstat and then return NULL. This will trigger the execution of the listen_overflow code in tcp_check_req:

        if (!sysctl_tcp_abort_on_overflow) {
                inet_rsk(req)->acked = 1;
                return NULL;

This means that unless /proc/sys/net/ipv4/tcp_abort_on_overflow is set to 1 (in which case the code right after the code shown above will send a RST packet), the implementation basically does... nothing!

To summarize, if the TCP implementation in Linux receives the ACK packet of the 3-way handshake and the accept queue is full, it will basically ignore that packet. At first, this sounds strange, but remember that there is a timer associated with the SYN RECEIVED state: if the ACK packet is not received (or if it is ignored, as in the case considered here), then the TCP implementation will resend the SYN/ACK packet (with a certain number of retries specified by /proc/sys/net/ipv4/tcp_synack_retries and using an exponential backoff algorithm).

This can be seen in the following packet trace for a client attempting to connect (and send data) to a socket that has reached its maximum backlog:

  0.000 ->  TCP 74 53302 > 9999 [SYN] Seq=0 Len=0
  0.000 ->  TCP 74 9999 > 53302 [SYN, ACK] Seq=0 Ack=1 Len=0
  0.000 ->  TCP 66 53302 > 9999 [ACK] Seq=1 Ack=1 Len=0
  0.000 ->  TCP 71 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
  0.207 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
  0.623 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
  1.199 ->  TCP 74 9999 > 53302 [SYN, ACK] Seq=0 Ack=1 Len=0
  1.199 ->  TCP 66 [TCP Dup ACK 6#1] 53302 > 9999 [ACK] Seq=6 Ack=1 Len=0
  1.455 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
  3.123 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
  3.399 ->  TCP 74 9999 > 53302 [SYN, ACK] Seq=0 Ack=1 Len=0
  3.399 ->  TCP 66 [TCP Dup ACK 10#1] 53302 > 9999 [ACK] Seq=6 Ack=1 Len=0
  6.459 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
  7.599 ->  TCP 74 9999 > 53302 [SYN, ACK] Seq=0 Ack=1 Len=0
  7.599 ->  TCP 66 [TCP Dup ACK 13#1] 53302 > 9999 [ACK] Seq=6 Ack=1 Len=0
 13.131 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
 15.599 ->  TCP 74 9999 > 53302 [SYN, ACK] Seq=0 Ack=1 Len=0
 15.599 ->  TCP 66 [TCP Dup ACK 16#1] 53302 > 9999 [ACK] Seq=6 Ack=1 Len=0
 26.491 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
 31.599 ->  TCP 74 9999 > 53302 [SYN, ACK] Seq=0 Ack=1 Len=0
 31.599 ->  TCP 66 [TCP Dup ACK 19#1] 53302 > 9999 [ACK] Seq=6 Ack=1 Len=0
 53.179 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
106.491 ->  TCP 71 [TCP Retransmission] 53302 > 9999 [PSH, ACK] Seq=1 Ack=1 Len=5
106.491 ->  TCP 54 9999 > 53302 [RST] Seq=1 Len=0

Since the TCP implementation on the client side gets multiple SYN/ACK packets, it will assume that the ACK packet was lost and resend it (see the lines with TCP Dup ACK in the above trace). If the application on the server side reduces the backlog (i.e. consumes an entry from the accept queue) before the maximum number of SYN/ACK retries has been reached, then the TCP implementation will eventually process one of the duplicate ACKs, transition the state of the connection from SYN RECEIVED to ESTABLISHED and add it to the accept queue. Otherwise, the client will eventually get a RST packet (as in the sample shown above).

The packet trace also shows another interesting aspect of this behavior. From the point of view of the client, the connection will be in state ESTABLISHED after reception of the first SYN/ACK. If it sends data (without waiting for data from the server first), then that data will be retransmitted as well. Fortunately TCP slow-start should limit the number of segments sent during this phase.

On the other hand, if the client first waits for data from the server and the server never reduces the backlog, then the end result is that on the client side, the connection is in state ESTABLISHED, while on the server side, the connection is considered CLOSED. This means that we end up with a half-open connection!

There is one other aspect that we didn't discuss yet. The quote from the listen man page suggests that every SYN packet would result in the addition of a connection to the SYN queue (unless that queue is full). That is not exactly how things work. The reason is the following code in the tcp_v4_conn_request function (which does the processing of SYN packets) in net/ipv4/tcp_ipv4.c:

        /* Accept backlog is full. If we have already queued enough
         * of warm entries in syn queue, drop request. It is better than
         * clogging syn queue with openreqs with exponentially increasing
         * timeout.
        if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) {
                NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
                goto drop;

What this means is that if the accept queue is full, then the kernel will impose a limit on the rate at which SYN packets are accepted. If too many SYN packets are received, some of them will be dropped. In this case, it is up to the client to retry sending the SYN packet and we end up with the same behavior as in BSD derived implementations.

To conclude, let's try to see why the design choice made by Linux would be superior to the traditional BSD implementation. Stevens makes the following interesting point:

The backlog can be reached if the completed connection queue fills (i.e., the server process or the server host is so busy that the process cannot call accept fast enough to take the completed entries off the queue) or if the incomplete connection queue fills. The latter is the problem that HTTP servers face, when the round-trip time between the client and server is long, compared to the arrival rate of new connection requests, because a new SYN occupies an entry on this queue for one round-trip time. [...]

The completed connection queue is almost always empty because when an entry is placed on this queue, the server's call to accept returns, and the server takes the completed connection off the queue.

The solution suggested by Stevens is simply to increase the backlog. The problem with this is that it assumes that an application is expected to tune the backlog not only taking into account how it intents to process newly established incoming connections, but also in function of traffic characteristics such as the round-trip time. The implementation in Linux effectively separates these two concerns: the application is only responsible for tuning the backlog such that it can call accept fast enough to avoid filling the accept queue); a system administrator can then tune /proc/sys/net/ipv4/tcp_max_syn_backlog based on traffic characteristics.