You are viewing a plain text version of this content. The canonical link for it is here.
Posted to common-commits@hadoop.apache.org by ki...@apache.org on 2016/09/01 21:16:04 UTC
[1/4] hadoop git commit: HADOOP-13426. More efficiently build IPC
responses. Contributed by Daryn Sharp.
Repository: hadoop
Updated Branches:
refs/heads/branch-2.8 22e182f29 -> 2ff6b13e6
HADOOP-13426. More efficiently build IPC responses. Contributed by Daryn Sharp.
(cherry picked from commit 2d8227605fe22c1c05f31729edc8939013763c05)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/afc8da0d
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/afc8da0d
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/afc8da0d
Branch: refs/heads/branch-2.8
Commit: afc8da0d8618f3852479d65864bb2d039842f564
Parents: 22e182f
Author: Kihwal Lee <ki...@apache.org>
Authored: Wed Aug 3 09:33:04 2016 -0500
Committer: Kihwal Lee <ki...@apache.org>
Committed: Thu Sep 1 15:59:40 2016 -0500
----------------------------------------------------------------------
.../org/apache/hadoop/ipc/ResponseBuffer.java | 98 +++++++++++++
.../main/java/org/apache/hadoop/ipc/Server.java | 143 +++++++++----------
.../apache/hadoop/ipc/TestResponseBuffer.java | 87 +++++++++++
3 files changed, 250 insertions(+), 78 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/afc8da0d/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ResponseBuffer.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ResponseBuffer.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ResponseBuffer.java
new file mode 100644
index 0000000..ac96a24
--- /dev/null
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ResponseBuffer.java
@@ -0,0 +1,98 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ipc;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Arrays;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+
+@InterfaceAudience.Private
+class ResponseBuffer extends DataOutputStream {
+ ResponseBuffer(int capacity) {
+ super(new FramedBuffer(capacity));
+ }
+
+ // update framing bytes based on bytes written to stream.
+ private FramedBuffer getFramedBuffer() {
+ FramedBuffer buf = (FramedBuffer)out;
+ buf.setSize(written);
+ return buf;
+ }
+
+ void writeTo(OutputStream out) throws IOException {
+ getFramedBuffer().writeTo(out);
+ }
+
+ byte[] toByteArray() {
+ return getFramedBuffer().toByteArray();
+ }
+
+ int capacity() {
+ return ((FramedBuffer)out).capacity();
+ }
+
+ void setCapacity(int capacity) {
+ ((FramedBuffer)out).setCapacity(capacity);
+ }
+
+ void ensureCapacity(int capacity) {
+ if (((FramedBuffer)out).capacity() < capacity) {
+ ((FramedBuffer)out).setCapacity(capacity);
+ }
+ }
+
+ ResponseBuffer reset() {
+ written = 0;
+ ((FramedBuffer)out).reset();
+ return this;
+ }
+
+ private static class FramedBuffer extends ByteArrayOutputStream {
+ private static final int FRAMING_BYTES = 4;
+ FramedBuffer(int capacity) {
+ super(capacity + FRAMING_BYTES);
+ reset();
+ }
+ @Override
+ public int size() {
+ return count - FRAMING_BYTES;
+ }
+ void setSize(int size) {
+ buf[0] = (byte)((size >>> 24) & 0xFF);
+ buf[1] = (byte)((size >>> 16) & 0xFF);
+ buf[2] = (byte)((size >>> 8) & 0xFF);
+ buf[3] = (byte)((size >>> 0) & 0xFF);
+ }
+ int capacity() {
+ return buf.length - FRAMING_BYTES;
+ }
+ void setCapacity(int capacity) {
+ buf = Arrays.copyOf(buf, capacity + FRAMING_BYTES);
+ }
+ @Override
+ public void reset() {
+ count = FRAMING_BYTES;
+ setSize(0);
+ }
+ };
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hadoop/blob/afc8da0d/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
index 5d3811a..a6413e7 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
@@ -79,12 +79,11 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
-import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.ipc.ProtobufRpcEngine.RpcResponseMessageWrapper;
import org.apache.hadoop.ipc.ProtobufRpcEngine.RpcResponseWrapper;
+import org.apache.hadoop.ipc.ProtobufRpcEngine.RpcWrapper;
import org.apache.hadoop.ipc.RPC.RpcInvoker;
import org.apache.hadoop.ipc.RPC.VersionMismatch;
import org.apache.hadoop.ipc.metrics.RpcDetailedMetrics;
@@ -422,6 +421,13 @@ public abstract class Server {
private int maxQueueSize;
private final int maxRespSize;
+ private final ThreadLocal<ResponseBuffer> responseBuffer =
+ new ThreadLocal<ResponseBuffer>(){
+ @Override
+ protected ResponseBuffer initialValue() {
+ return new ResponseBuffer(INITIAL_RESP_BUF_SIZE);
+ }
+ };
private int socketSendBufferSize;
private final int maxDataLength;
private final boolean tcpNoDelay; // if T then disable Nagle's Algorithm
@@ -743,14 +749,7 @@ public abstract class Server {
public void abortResponse(Throwable t) throws IOException {
// don't send response if the call was already sent or aborted.
if (responseWaitCount.getAndSet(-1) > 0) {
- // clone the call to prevent a race with the other thread stomping
- // on the response while being sent. the original call is
- // effectively discarded since the wait count won't hit zero
- Call call = new Call(this);
- setupResponse(new ByteArrayOutputStream(), call,
- RpcStatusProto.FATAL, RpcErrorCodeProto.ERROR_RPC_SERVER,
- null, t.getClass().getName(), StringUtils.stringifyException(t));
- call.sendResponse();
+ connection.abortResponse(this, t);
}
}
@@ -1271,9 +1270,7 @@ public abstract class Server {
// must only wrap before adding to the responseQueue to prevent
// postponed responses from being encrypted and sent out of order.
if (call.connection.useWrap) {
- ByteArrayOutputStream response = new ByteArrayOutputStream();
- wrapWithSasl(response, call);
- call.setResponse(ByteBuffer.wrap(response.toByteArray()));
+ wrapWithSasl(call);
}
call.connection.responseQueue.addLast(call);
if (call.connection.responseQueue.size() == 1) {
@@ -1394,8 +1391,7 @@ public abstract class Server {
// Fake 'call' for failed authorization response
private final Call authFailedCall = new Call(AUTHORIZATION_FAILED_CALL_ID,
RpcConstants.INVALID_RETRY_COUNT, null, this);
- private ByteArrayOutputStream authFailedResponse = new ByteArrayOutputStream();
-
+
private boolean sentNegotiate = false;
private boolean useWrap = false;
@@ -1674,15 +1670,14 @@ public abstract class Server {
private void doSaslReply(Message message) throws IOException {
final Call saslCall = new Call(AuthProtocol.SASL.callId,
RpcConstants.INVALID_RETRY_COUNT, null, this);
- final ByteArrayOutputStream saslResponse = new ByteArrayOutputStream();
- setupResponse(saslResponse, saslCall,
+ setupResponse(saslCall,
RpcStatusProto.SUCCESS, null,
new RpcResponseWrapper(message), null, null);
saslCall.sendResponse();
}
private void doSaslReply(Exception ioe) throws IOException {
- setupResponse(authFailedResponse, authFailedCall,
+ setupResponse(authFailedCall,
RpcStatusProto.FATAL, RpcErrorCodeProto.FATAL_UNAUTHORIZED,
null, ioe.getClass().getName(), ioe.getLocalizedMessage());
authFailedCall.sendResponse();
@@ -1860,7 +1855,7 @@ public abstract class Server {
// Versions >>9 understand the normal response
Call fakeCall = new Call(-1, RpcConstants.INVALID_RETRY_COUNT, null,
this);
- setupResponse(buffer, fakeCall,
+ setupResponse(fakeCall,
RpcStatusProto.FATAL, RpcErrorCodeProto.FATAL_VERSION_MISMATCH,
null, VersionMismatch.class.getName(), errMsg);
fakeCall.sendResponse();
@@ -2026,7 +2021,7 @@ public abstract class Server {
} catch (WrappedRpcServerException wrse) { // inform client of error
Throwable ioe = wrse.getCause();
final Call call = new Call(callId, retry, null, this);
- setupResponse(authFailedResponse, call,
+ setupResponse(call,
RpcStatusProto.FATAL, wrse.getRpcErrorCodeProto(), null,
ioe.getClass().getName(), ioe.getMessage());
call.sendResponse();
@@ -2252,6 +2247,17 @@ public abstract class Server {
responder.doRespond(call);
}
+ private void abortResponse(Call call, Throwable t) throws IOException {
+ // clone the call to prevent a race with the other thread stomping
+ // on the response while being sent. the original call is
+ // effectively discarded since the wait count won't hit zero
+ call = new Call(call);
+ setupResponse(call,
+ RpcStatusProto.FATAL, RpcErrorCodeProto.ERROR_RPC_SERVER,
+ null, t.getClass().getName(), StringUtils.stringifyException(t));
+ call.sendResponse();
+ }
+
/**
* Get service class for connection
* @return the serviceClass
@@ -2295,8 +2301,6 @@ public abstract class Server {
public void run() {
LOG.debug(Thread.currentThread().getName() + ": starting");
SERVER.set(Server.this);
- ByteArrayOutputStream buf =
- new ByteArrayOutputStream(INITIAL_RESP_BUF_SIZE);
while (running) {
TraceScope traceScope = null;
try {
@@ -2366,16 +2370,8 @@ public abstract class Server {
}
CurCall.set(null);
synchronized (call.connection.responseQueue) {
- setupResponse(buf, call, returnStatus, detailedErr,
+ setupResponse(call, returnStatus, detailedErr,
value, errorClass, error);
-
- // Discard the large buf and reset it back to smaller size
- // to free up heap.
- if (buf.size() > maxRespSize) {
- LOG.warn("Large response size " + buf.size() + " for call "
- + call.toString());
- buf = new ByteArrayOutputStream(INITIAL_RESP_BUF_SIZE);
- }
call.sendResponse();
}
} catch (InterruptedException e) {
@@ -2593,13 +2589,11 @@ public abstract class Server {
* @param error error message, if the call failed
* @throws IOException
*/
- private static void setupResponse(ByteArrayOutputStream responseBuf,
- Call call, RpcStatusProto status, RpcErrorCodeProto erCode,
- Writable rv, String errorClass, String error)
- throws IOException {
- responseBuf.reset();
- DataOutputStream out = new DataOutputStream(responseBuf);
- RpcResponseHeaderProto.Builder headerBuilder =
+ private void setupResponse(
+ Call call, RpcStatusProto status, RpcErrorCodeProto erCode,
+ Writable rv, String errorClass, String error)
+ throws IOException {
+ RpcResponseHeaderProto.Builder headerBuilder =
RpcResponseHeaderProto.newBuilder();
headerBuilder.setClientId(ByteString.copyFrom(call.clientId));
headerBuilder.setCallId(call.callId);
@@ -2609,32 +2603,14 @@ public abstract class Server {
if (status == RpcStatusProto.SUCCESS) {
RpcResponseHeaderProto header = headerBuilder.build();
- final int headerLen = header.getSerializedSize();
- int fullLength = CodedOutputStream.computeRawVarint32Size(headerLen) +
- headerLen;
try {
- if (rv instanceof ProtobufRpcEngine.RpcWrapper) {
- ProtobufRpcEngine.RpcWrapper resWrapper =
- (ProtobufRpcEngine.RpcWrapper) rv;
- fullLength += resWrapper.getLength();
- out.writeInt(fullLength);
- header.writeDelimitedTo(out);
- rv.write(out);
- } else { // Have to serialize to buffer to get len
- final DataOutputBuffer buf = new DataOutputBuffer();
- rv.write(buf);
- byte[] data = buf.getData();
- fullLength += buf.getLength();
- out.writeInt(fullLength);
- header.writeDelimitedTo(out);
- out.write(data, 0, buf.getLength());
- }
+ setupResponse(call, header, rv);
} catch (Throwable t) {
LOG.warn("Error serializing call response for call " + call, t);
// Call back to same function - this is OK since the
// buffer is reset at the top, and since status is changed
// to ERROR it won't infinite loop.
- setupResponse(responseBuf, call, RpcStatusProto.ERROR,
+ setupResponse(call, RpcStatusProto.ERROR,
RpcErrorCodeProto.ERROR_SERIALIZING_RESPONSE,
null, t.getClass().getName(),
StringUtils.stringifyException(t));
@@ -2644,16 +2620,35 @@ public abstract class Server {
headerBuilder.setExceptionClassName(errorClass);
headerBuilder.setErrorMsg(error);
headerBuilder.setErrorDetail(erCode);
- RpcResponseHeaderProto header = headerBuilder.build();
- int headerLen = header.getSerializedSize();
- final int fullLength =
- CodedOutputStream.computeRawVarint32Size(headerLen) + headerLen;
- out.writeInt(fullLength);
- header.writeDelimitedTo(out);
+ setupResponse(call, headerBuilder.build(), null);
}
- call.setResponse(ByteBuffer.wrap(responseBuf.toByteArray()));
}
-
+
+ private void setupResponse(Call call,
+ RpcResponseHeaderProto header, Writable rv) throws IOException {
+ ResponseBuffer buf = responseBuffer.get().reset();
+ // adjust capacity on estimated length to reduce resizing copies
+ int estimatedLen = header.getSerializedSize();
+ estimatedLen += CodedOutputStream.computeRawVarint32Size(estimatedLen);
+ // if it's not a wrapped protobuf, just let it grow on its own
+ if (rv instanceof RpcWrapper) {
+ estimatedLen += ((RpcWrapper)rv).getLength();
+ }
+ buf.ensureCapacity(estimatedLen);
+ header.writeDelimitedTo(buf);
+ if (rv != null) { // null for exceptions
+ rv.write(buf);
+ }
+ call.setResponse(ByteBuffer.wrap(buf.toByteArray()));
+ // Discard a large buf and reset it back to smaller size
+ // to free up heap.
+ if (buf.capacity() > maxRespSize) {
+ LOG.warn("Large response size " + buf.size() + " for call "
+ + call.toString());
+ buf.setCapacity(INITIAL_RESP_BUF_SIZE);
+ }
+ }
+
/**
* Setup response for the IPC Call on Fatal Error from a
* client that is using old version of Hadoop.
@@ -2680,10 +2675,8 @@ public abstract class Server {
WritableUtils.writeString(out, error);
call.setResponse(ByteBuffer.wrap(response.toByteArray()));
}
-
-
- private static void wrapWithSasl(ByteArrayOutputStream response, Call call)
- throws IOException {
+
+ private void wrapWithSasl(Call call) throws IOException {
if (call.connection.saslServer != null) {
byte[] token = call.rpcResponse.array();
// synchronization may be needed since there can be multiple Handler
@@ -2694,7 +2687,6 @@ public abstract class Server {
if (LOG.isDebugEnabled())
LOG.debug("Adding saslServer wrapped token of size " + token.length
+ " as call response.");
- response.reset();
// rebuild with sasl header and payload
RpcResponseHeaderProto saslHeader = RpcResponseHeaderProto.newBuilder()
.setCallId(AuthProtocol.SASL.callId)
@@ -2702,14 +2694,9 @@ public abstract class Server {
.build();
RpcSaslProto saslMessage = RpcSaslProto.newBuilder()
.setState(SaslState.WRAP)
- .setToken(ByteString.copyFrom(token, 0, token.length))
+ .setToken(ByteString.copyFrom(token))
.build();
- RpcResponseMessageWrapper saslResponse =
- new RpcResponseMessageWrapper(saslHeader, saslMessage);
-
- DataOutputStream out = new DataOutputStream(response);
- out.writeInt(saslResponse.getLength());
- saslResponse.write(out);
+ setupResponse(call, saslHeader, new RpcResponseWrapper(saslMessage));
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/afc8da0d/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestResponseBuffer.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestResponseBuffer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestResponseBuffer.java
new file mode 100644
index 0000000..98743be
--- /dev/null
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestResponseBuffer.java
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ipc;
+
+import static org.junit.Assert.assertEquals;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+import org.apache.hadoop.ipc.ResponseBuffer;
+import org.junit.Test;
+
+/** Unit tests for ResponseBuffer. */
+public class TestResponseBuffer {
+ @Test
+ public void testBuffer() throws IOException {
+ final int startSize = 8;
+ final String empty = "";
+ ResponseBuffer buf = new ResponseBuffer(startSize);
+ assertEquals(startSize, buf.capacity());
+
+ // verify it's initially empty
+ checkBuffer(buf, empty);
+ // write "nothing" and re-verify it's empty
+ buf.writeBytes(empty);
+ checkBuffer(buf, empty);
+
+ // write to the buffer twice and verify it's properly encoded
+ String s1 = "testing123";
+ buf.writeBytes(s1);
+ checkBuffer(buf, s1);
+ String s2 = "456!";
+ buf.writeBytes(s2);
+ checkBuffer(buf, s1 + s2);
+
+ // reset should not change length of underlying byte array
+ int length = buf.capacity();
+ buf.reset();
+ assertEquals(length, buf.capacity());
+ checkBuffer(buf, empty);
+
+ // setCapacity will change length of underlying byte array
+ buf.setCapacity(startSize);
+ assertEquals(startSize, buf.capacity());
+ checkBuffer(buf, empty);
+
+ // make sure it still works
+ buf.writeBytes(s1);
+ checkBuffer(buf, s1);
+ buf.writeBytes(s2);
+ checkBuffer(buf, s1 + s2);
+ }
+
+ private void checkBuffer(ResponseBuffer buf, String expected)
+ throws IOException {
+ // buffer payload length matches expected length
+ int expectedLength = expected.getBytes().length;
+ assertEquals(expectedLength, buf.size());
+ // buffer has the framing bytes (int)
+ byte[] framed = buf.toByteArray();
+ assertEquals(expectedLength + 4, framed.length);
+
+ // verify encoding of buffer: framing (int) + payload bytes
+ DataInputStream dis =
+ new DataInputStream(new ByteArrayInputStream(framed));
+ assertEquals(expectedLength, dis.readInt());
+ assertEquals(expectedLength, dis.available());
+ byte[] payload = new byte[expectedLength];
+ dis.readFully(payload);
+ assertEquals(expected, new String(payload));
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org
[2/4] hadoop git commit: HADOOP-13429. Dispose of unnecessary SASL
servers. Contributed by Daryn Sharp.
Posted by ki...@apache.org.
HADOOP-13429. Dispose of unnecessary SASL servers. Contributed by Daryn Sharp.
(cherry picked from commit b3018e73ccae43484d9cb85eabae814eb7f050a6)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/983d47ec
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/983d47ec
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/983d47ec
Branch: refs/heads/branch-2.8
Commit: 983d47ecb300dac79db22aa54a6c681dc636819b
Parents: afc8da0
Author: Kihwal Lee <ki...@apache.org>
Authored: Tue Aug 2 10:52:10 2016 -0500
Committer: Kihwal Lee <ki...@apache.org>
Committed: Thu Sep 1 15:59:53 2016 -0500
----------------------------------------------------------------------
.../src/main/java/org/apache/hadoop/ipc/Server.java | 13 +++++++++----
.../test/java/org/apache/hadoop/ipc/TestSaslRPC.java | 12 +++++++++++-
2 files changed, 20 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/983d47ec/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
index a6413e7..a0402c2 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
@@ -1569,7 +1569,10 @@ public abstract class Server {
String qop = (String) saslServer.getNegotiatedProperty(Sasl.QOP);
// SASL wrapping is only used if the connection has a QOP, and
// the value is not auth. ex. auth-int & auth-priv
- useWrap = (qop != null && !"auth".equalsIgnoreCase(qop));
+ useWrap = (qop != null && !"auth".equalsIgnoreCase(qop));
+ if (!useWrap) {
+ disposeSasl();
+ }
}
}
@@ -1650,9 +1653,9 @@ public abstract class Server {
private void switchToSimple() {
// disable SASL and blank out any SASL server
authProtocol = AuthProtocol.NONE;
- saslServer = null;
+ disposeSasl();
}
-
+
private RpcSaslProto buildSaslResponse(SaslState state, byte[] replyToken) {
if (LOG.isDebugEnabled()) {
LOG.debug("Will send " + state + " token of size "
@@ -1688,6 +1691,8 @@ public abstract class Server {
try {
saslServer.dispose();
} catch (SaslException ignored) {
+ } finally {
+ saslServer = null;
}
}
}
@@ -1906,7 +1911,7 @@ public abstract class Server {
.getProtocol() : null;
UserGroupInformation protocolUser = ProtoUtil.getUgi(connectionContext);
- if (saslServer == null) {
+ if (authProtocol == AuthProtocol.NONE) {
user = protocolUser;
} else {
// user is authenticated
http://git-wip-us.apache.org/repos/asf/hadoop/blob/983d47ec/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestSaslRPC.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestSaslRPC.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestSaslRPC.java
index ec53e8c..72371a7 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestSaslRPC.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestSaslRPC.java
@@ -28,6 +28,7 @@ import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.Client.ConnectionId;
+import org.apache.hadoop.ipc.Server.Connection;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.*;
import org.apache.hadoop.security.SaslRpcServer.AuthMethod;
@@ -270,7 +271,16 @@ public class TestSaslRPC extends TestRpcBase {
assertEquals(TOKEN, authMethod);
//QOP must be auth
assertEquals(expectedQop.saslQop,
- RPC.getConnectionIdForProxy(proxy).getSaslQop());
+ RPC.getConnectionIdForProxy(proxy).getSaslQop());
+ int n = 0;
+ for (Connection connection : server.getConnections()) {
+ // only qop auth should dispose of the sasl server
+ boolean hasServer = (connection.saslServer != null);
+ assertTrue("qop:" + expectedQop + " hasServer:" + hasServer,
+ (expectedQop == QualityOfProtection.AUTHENTICATION) ^ hasServer);
+ n++;
+ }
+ assertTrue(n > 0);
proxy.ping(null, newEmptyRequest());
} finally {
stop(server, proxy);
---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org
[3/4] hadoop git commit: HADOOP-13483. Optimize IPC server protobuf
decoding. Contributed by Daryn Sharp.
Posted by ki...@apache.org.
HADOOP-13483. Optimize IPC server protobuf decoding. Contributed by Daryn Sharp.
(cherry picked from commit 580a8334963709e728ed677c815fb7fef9bca70e)
Conflicts:
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/a4292fe6
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/a4292fe6
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/a4292fe6
Branch: refs/heads/branch-2.8
Commit: a4292fe6187eeb9a159160983df98fcc38326188
Parents: 983d47e
Author: Kihwal Lee <ki...@apache.org>
Authored: Wed Aug 3 14:12:02 2016 -0500
Committer: Kihwal Lee <ki...@apache.org>
Committed: Thu Sep 1 16:00:55 2016 -0500
----------------------------------------------------------------------
.../apache/hadoop/ipc/ProtobufRpcEngine.java | 15 +-
.../java/org/apache/hadoop/ipc/RpcWritable.java | 184 +++++++++++++++++++
.../main/java/org/apache/hadoop/ipc/Server.java | 94 ++++------
.../org/apache/hadoop/ipc/TestRpcWritable.java | 129 +++++++++++++
4 files changed, 361 insertions(+), 61 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/a4292fe6/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
index ea629b1..cfdf8ab 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
@@ -32,6 +32,7 @@ import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.ipc.Client.ConnectionId;
import org.apache.hadoop.ipc.RPC.RpcInvoker;
+import org.apache.hadoop.ipc.RpcWritable;
import org.apache.hadoop.ipc.protobuf.ProtobufRpcEngineProtos.RequestHeaderProto;
import org.apache.hadoop.ipc.protobuf.RpcHeaderProtos.RpcRequestHeaderProto;
import org.apache.hadoop.ipc.protobuf.RpcHeaderProtos.RpcResponseHeaderProto;
@@ -68,7 +69,7 @@ public class ProtobufRpcEngine implements RpcEngine {
static { // Register the rpcRequest deserializer for WritableRpcEngine
org.apache.hadoop.ipc.Server.registerProtocolEngine(
- RPC.RpcKind.RPC_PROTOCOL_BUFFER, RpcRequestWrapper.class,
+ RPC.RpcKind.RPC_PROTOCOL_BUFFER, RpcWritable.Buffer.class,
new Server.ProtoBufRpcInvoker());
}
@@ -612,8 +613,9 @@ public class ProtobufRpcEngine implements RpcEngine {
*/
public Writable call(RPC.Server server, String protocol,
Writable writableRequest, long receiveTime) throws Exception {
- RpcRequestWrapper request = (RpcRequestWrapper) writableRequest;
- RequestHeaderProto rpcRequest = request.requestHeader;
+ RpcWritable.Buffer request = (RpcWritable.Buffer) writableRequest;
+ RequestHeaderProto rpcRequest =
+ request.getValue(RequestHeaderProto.getDefaultInstance());
String methodName = rpcRequest.getMethodName();
String protoName = rpcRequest.getDeclaringClassProtocolName();
long clientVersion = rpcRequest.getClientProtocolVersion();
@@ -632,9 +634,8 @@ public class ProtobufRpcEngine implements RpcEngine {
throw new RpcNoSuchMethodException(msg);
}
Message prototype = service.getRequestPrototype(methodDescriptor);
- Message param = prototype.newBuilderForType()
- .mergeFrom(request.theRequestRead).build();
-
+ Message param = request.getValue(prototype);
+
Message result;
long startTime = Time.now();
int qTime = (int) (startTime - receiveTime);
@@ -663,7 +664,7 @@ public class ProtobufRpcEngine implements RpcEngine {
exception.getClass().getSimpleName();
server.updateMetrics(detailedMetricsName, qTime, processingTime);
}
- return new RpcResponseWrapper(result);
+ return RpcWritable.wrap(result);
}
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/a4292fe6/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RpcWritable.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RpcWritable.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RpcWritable.java
new file mode 100644
index 0000000..5125939
--- /dev/null
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RpcWritable.java
@@ -0,0 +1,184 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ipc;
+
+import java.io.ByteArrayInputStream;
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.conf.Configurable;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.Writable;
+
+import com.google.protobuf.CodedInputStream;
+import com.google.protobuf.CodedOutputStream;
+import com.google.protobuf.Message;
+
+@InterfaceAudience.Private
+public abstract class RpcWritable implements Writable {
+
+ static RpcWritable wrap(Object o) {
+ if (o instanceof RpcWritable) {
+ return (RpcWritable)o;
+ } else if (o instanceof Message) {
+ return new ProtobufWrapper((Message)o);
+ } else if (o instanceof Writable) {
+ return new WritableWrapper((Writable)o);
+ }
+ throw new IllegalArgumentException("Cannot wrap " + o.getClass());
+ }
+
+ // don't support old inefficient Writable methods.
+ @Override
+ public final void readFields(DataInput in) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+ @Override
+ public final void write(DataOutput out) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ // methods optimized for reduced intermediate byte[] allocations.
+ abstract void writeTo(ResponseBuffer out) throws IOException;
+ abstract <T> T readFrom(ByteBuffer bb) throws IOException;
+
+ // adapter for Writables.
+ static class WritableWrapper extends RpcWritable {
+ private final Writable writable;
+
+ WritableWrapper(Writable writable) {
+ this.writable = writable;
+ }
+
+ @Override
+ public void writeTo(ResponseBuffer out) throws IOException {
+ writable.write(out);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ <T> T readFrom(ByteBuffer bb) throws IOException {
+ // create a stream that may consume up to the entire ByteBuffer.
+ DataInputStream in = new DataInputStream(new ByteArrayInputStream(
+ bb.array(), bb.position() + bb.arrayOffset(), bb.remaining()));
+ try {
+ writable.readFields(in);
+ } finally {
+ // advance over the bytes read.
+ bb.position(bb.limit() - in.available());
+ }
+ return (T)writable;
+ }
+ }
+
+ // adapter for Protobufs.
+ static class ProtobufWrapper extends RpcWritable {
+ private Message message;
+
+ ProtobufWrapper(Message message) {
+ this.message = message;
+ }
+
+ @Override
+ void writeTo(ResponseBuffer out) throws IOException {
+ int length = message.getSerializedSize();
+ length += CodedOutputStream.computeRawVarint32Size(length);
+ out.ensureCapacity(length);
+ message.writeDelimitedTo(out);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ <T> T readFrom(ByteBuffer bb) throws IOException {
+ // using the parser with a byte[]-backed coded input stream is the
+ // most efficient way to deserialize a protobuf. it has a direct
+ // path to the PB ctor that doesn't create multi-layered streams
+ // that internally buffer.
+ CodedInputStream cis = CodedInputStream.newInstance(
+ bb.array(), bb.position() + bb.arrayOffset(), bb.remaining());
+ try {
+ cis.pushLimit(cis.readRawVarint32());
+ message = message.getParserForType().parseFrom(cis);
+ cis.checkLastTagWas(0);
+ } finally {
+ // advance over the bytes read.
+ bb.position(bb.position() + cis.getTotalBytesRead());
+ }
+ return (T)message;
+ }
+ }
+
+ // adapter to allow decoding of writables and protobufs from a byte buffer.
+ static class Buffer extends RpcWritable {
+ private ByteBuffer bb;
+
+ static Buffer wrap(ByteBuffer bb) {
+ return new Buffer(bb);
+ }
+
+ Buffer() {}
+
+ Buffer(ByteBuffer bb) {
+ this.bb = bb;
+ }
+
+ @Override
+ void writeTo(ResponseBuffer out) throws IOException {
+ out.ensureCapacity(bb.remaining());
+ out.write(bb.array(), bb.position() + bb.arrayOffset(), bb.remaining());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ <T> T readFrom(ByteBuffer bb) throws IOException {
+ // effectively consume the rest of the buffer from the callers
+ // perspective.
+ this.bb = bb.slice();
+ bb.limit(bb.position());
+ return (T)this;
+ }
+
+ public <T> T newInstance(Class<T> valueClass,
+ Configuration conf) throws IOException {
+ T instance;
+ try {
+ // this is much faster than ReflectionUtils!
+ instance = valueClass.newInstance();
+ if (instance instanceof Configurable) {
+ ((Configurable)instance).setConf(conf);
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return getValue(instance);
+ }
+
+ public <T> T getValue(T value) throws IOException {
+ return RpcWritable.wrap(value).readFrom(bb);
+ }
+
+ int remaining() {
+ return bb.remaining();
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hadoop/blob/a4292fe6/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
index a0402c2..d7a2673c 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
@@ -25,7 +25,6 @@ import static org.apache.hadoop.ipc.RpcConstants.PING_CALL_ID;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
@@ -82,8 +81,6 @@ import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.ipc.ProtobufRpcEngine.RpcResponseWrapper;
-import org.apache.hadoop.ipc.ProtobufRpcEngine.RpcWrapper;
import org.apache.hadoop.ipc.RPC.RpcInvoker;
import org.apache.hadoop.ipc.RPC.VersionMismatch;
import org.apache.hadoop.ipc.metrics.RpcDetailedMetrics;
@@ -113,7 +110,6 @@ import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.ProtoUtil;
-import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Time;
import org.apache.htrace.core.SpanId;
@@ -122,9 +118,7 @@ import org.apache.htrace.core.Tracer;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
-import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;
-import com.google.protobuf.Message.Builder;
/** An abstract IPC service. IPC calls take a single {@link Writable} as a
* parameter, and return a {@link Writable} as their value. A service runs on
@@ -1345,6 +1339,7 @@ public abstract class Server {
* A WrappedRpcServerException that is suppressed altogether
* for the purposes of logging.
*/
+ @SuppressWarnings("serial")
private static class WrappedRpcServerExceptionSuppressed
extends WrappedRpcServerException {
public WrappedRpcServerExceptionSuppressed(
@@ -1474,10 +1469,10 @@ public abstract class Server {
}
}
- private void saslReadAndProcess(DataInputStream dis) throws
+ private void saslReadAndProcess(RpcWritable.Buffer buffer) throws
WrappedRpcServerException, IOException, InterruptedException {
final RpcSaslProto saslMessage =
- decodeProtobufFromStream(RpcSaslProto.newBuilder(), dis);
+ getMessage(RpcSaslProto.getDefaultInstance(), buffer);
switch (saslMessage.getState()) {
case WRAP: {
if (!saslContextEstablished || !useWrap) {
@@ -1675,7 +1670,7 @@ public abstract class Server {
RpcConstants.INVALID_RETRY_COUNT, null, this);
setupResponse(saslCall,
RpcStatusProto.SUCCESS, null,
- new RpcResponseWrapper(message), null, null);
+ RpcWritable.wrap(message), null, null);
saslCall.sendResponse();
}
@@ -1780,7 +1775,7 @@ public abstract class Server {
dataLengthBuffer.clear();
data.flip();
boolean isHeaderRead = connectionContextRead;
- processOneRpc(data.array());
+ processOneRpc(data);
data = null;
if (!isHeaderRead) {
continue;
@@ -1897,7 +1892,7 @@ public abstract class Server {
* @throws WrappedRpcServerException - if the header cannot be
* deserialized, or the user is not authorized
*/
- private void processConnectionContext(DataInputStream dis)
+ private void processConnectionContext(RpcWritable.Buffer buffer)
throws WrappedRpcServerException {
// allow only one connection context during a session
if (connectionContextRead) {
@@ -1905,8 +1900,7 @@ public abstract class Server {
RpcErrorCodeProto.FATAL_INVALID_RPC_HEADER,
"Connection context already processed");
}
- connectionContext = decodeProtobufFromStream(
- IpcConnectionContextProto.newBuilder(), dis);
+ connectionContext = getMessage(IpcConnectionContextProto.getDefaultInstance(), buffer);
protocolName = connectionContext.hasProtocol() ? connectionContext
.getProtocol() : null;
@@ -1981,7 +1975,7 @@ public abstract class Server {
if (unwrappedData.remaining() == 0) {
unwrappedDataLengthBuffer.clear();
unwrappedData.flip();
- processOneRpc(unwrappedData.array());
+ processOneRpc(unwrappedData);
unwrappedData = null;
}
}
@@ -1997,31 +1991,30 @@ public abstract class Server {
* the client that does not require verbose logging by the
* Listener thread
* @throws InterruptedException
- */
- private void processOneRpc(byte[] buf)
+ */
+ private void processOneRpc(ByteBuffer bb)
throws IOException, WrappedRpcServerException, InterruptedException {
int callId = -1;
int retry = RpcConstants.INVALID_RETRY_COUNT;
try {
- final DataInputStream dis =
- new DataInputStream(new ByteArrayInputStream(buf));
+ final RpcWritable.Buffer buffer = RpcWritable.Buffer.wrap(bb);
final RpcRequestHeaderProto header =
- decodeProtobufFromStream(RpcRequestHeaderProto.newBuilder(), dis);
+ getMessage(RpcRequestHeaderProto.getDefaultInstance(), buffer);
callId = header.getCallId();
retry = header.getRetryCount();
if (LOG.isDebugEnabled()) {
LOG.debug(" got #" + callId);
}
checkRpcHeaders(header);
-
+
if (callId < 0) { // callIds typically used during connection setup
- processRpcOutOfBandRequest(header, dis);
+ processRpcOutOfBandRequest(header, buffer);
} else if (!connectionContextRead) {
throw new WrappedRpcServerException(
RpcErrorCodeProto.FATAL_INVALID_RPC_HEADER,
"Connection context not established");
} else {
- processRpcRequest(header, dis);
+ processRpcRequest(header, buffer);
}
} catch (WrappedRpcServerException wrse) { // inform client of error
Throwable ioe = wrse.getCause();
@@ -2074,7 +2067,7 @@ public abstract class Server {
* @throws InterruptedException
*/
private void processRpcRequest(RpcRequestHeaderProto header,
- DataInputStream dis) throws WrappedRpcServerException,
+ RpcWritable.Buffer buffer) throws WrappedRpcServerException,
InterruptedException {
Class<? extends Writable> rpcRequestClass =
getRpcRequestWrapper(header.getRpcKind());
@@ -2088,8 +2081,7 @@ public abstract class Server {
}
Writable rpcRequest;
try { //Read the rpc request
- rpcRequest = ReflectionUtils.newInstance(rpcRequestClass, conf);
- rpcRequest.readFields(dis);
+ rpcRequest = buffer.newInstance(rpcRequestClass, conf);
} catch (Throwable t) { // includes runtime exception from newInstance
LOG.warn("Unable to read call parameters for client " +
getHostAddress() + "on connection protocol " +
@@ -2169,8 +2161,8 @@ public abstract class Server {
* @throws InterruptedException
*/
private void processRpcOutOfBandRequest(RpcRequestHeaderProto header,
- DataInputStream dis) throws WrappedRpcServerException, IOException,
- InterruptedException {
+ RpcWritable.Buffer buffer) throws WrappedRpcServerException,
+ IOException, InterruptedException {
final int callId = header.getCallId();
if (callId == CONNECTION_CONTEXT_CALL_ID) {
// SASL must be established prior to connection context
@@ -2180,7 +2172,7 @@ public abstract class Server {
"Connection header sent during SASL negotiation");
}
// read and authorize the user
- processConnectionContext(dis);
+ processConnectionContext(buffer);
} else if (callId == AuthProtocol.SASL.callId) {
// if client was switched to simple, ignore first SASL message
if (authProtocol != AuthProtocol.SASL) {
@@ -2188,7 +2180,7 @@ public abstract class Server {
RpcErrorCodeProto.FATAL_INVALID_RPC_HEADER,
"SASL protocol not requested by client");
}
- saslReadAndProcess(dis);
+ saslReadAndProcess(buffer);
} else if (callId == PING_CALL_ID) {
LOG.debug("Received ping message");
} else {
@@ -2235,13 +2227,12 @@ public abstract class Server {
* @throws WrappedRpcServerException - deserialization failed
*/
@SuppressWarnings("unchecked")
- private <T extends Message> T decodeProtobufFromStream(Builder builder,
- DataInputStream dis) throws WrappedRpcServerException {
+ <T extends Message> T getMessage(Message message,
+ RpcWritable.Buffer buffer) throws WrappedRpcServerException {
try {
- builder.mergeDelimitedFrom(dis);
- return (T)builder.build();
+ return (T)buffer.getValue(message);
} catch (Exception ioe) {
- Class<?> protoClass = builder.getDefaultInstanceForType().getClass();
+ Class<?> protoClass = message.getClass();
throw new WrappedRpcServerException(
RpcErrorCodeProto.FATAL_DESERIALIZING_REQUEST,
"Error decoding " + protoClass.getSimpleName() + ": "+ ioe);
@@ -2632,25 +2623,20 @@ public abstract class Server {
private void setupResponse(Call call,
RpcResponseHeaderProto header, Writable rv) throws IOException {
ResponseBuffer buf = responseBuffer.get().reset();
- // adjust capacity on estimated length to reduce resizing copies
- int estimatedLen = header.getSerializedSize();
- estimatedLen += CodedOutputStream.computeRawVarint32Size(estimatedLen);
- // if it's not a wrapped protobuf, just let it grow on its own
- if (rv instanceof RpcWrapper) {
- estimatedLen += ((RpcWrapper)rv).getLength();
- }
- buf.ensureCapacity(estimatedLen);
- header.writeDelimitedTo(buf);
- if (rv != null) { // null for exceptions
- rv.write(buf);
- }
- call.setResponse(ByteBuffer.wrap(buf.toByteArray()));
- // Discard a large buf and reset it back to smaller size
- // to free up heap.
- if (buf.capacity() > maxRespSize) {
- LOG.warn("Large response size " + buf.size() + " for call "
- + call.toString());
- buf.setCapacity(INITIAL_RESP_BUF_SIZE);
+ try {
+ RpcWritable.wrap(header).writeTo(buf);
+ if (rv != null) {
+ RpcWritable.wrap(rv).writeTo(buf);
+ }
+ call.setResponse(ByteBuffer.wrap(buf.toByteArray()));
+ } finally {
+ // Discard a large buf and reset it back to smaller size
+ // to free up heap.
+ if (buf.capacity() > maxRespSize) {
+ LOG.warn("Large response size " + buf.size() + " for call "
+ + call.toString());
+ buf.setCapacity(INITIAL_RESP_BUF_SIZE);
+ }
}
}
@@ -2701,7 +2687,7 @@ public abstract class Server {
.setState(SaslState.WRAP)
.setToken(ByteString.copyFrom(token))
.build();
- setupResponse(call, saslHeader, new RpcResponseWrapper(saslMessage));
+ setupResponse(call, saslHeader, RpcWritable.wrap(saslMessage));
}
}
http://git-wip-us.apache.org/repos/asf/hadoop/blob/a4292fe6/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRpcWritable.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRpcWritable.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRpcWritable.java
new file mode 100644
index 0000000..837f579
--- /dev/null
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRpcWritable.java
@@ -0,0 +1,129 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ipc;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import org.apache.hadoop.io.LongWritable;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.ipc.protobuf.TestProtos.EchoRequestProto;
+import org.apache.hadoop.util.Time;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.protobuf.Message;
+
+public class TestRpcWritable {//extends TestRpcBase {
+
+ static Writable writable = new LongWritable(Time.now());
+ static Message message1 =
+ EchoRequestProto.newBuilder().setMessage("testing1").build();
+ static Message message2 =
+ EchoRequestProto.newBuilder().setMessage("testing2").build();
+
+ @Test
+ public void testWritableWrapper() throws IOException {
+ // serial writable in byte buffer
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ writable.write(new DataOutputStream(baos));
+ ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
+
+ // deserial
+ LongWritable actual = RpcWritable.wrap(new LongWritable())
+ .readFrom(bb);
+ Assert.assertEquals(writable, actual);
+ Assert.assertEquals(0, bb.remaining());
+ }
+
+ @Test
+ public void testProtobufWrapper() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ message1.writeDelimitedTo(baos);
+ ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
+
+ Message actual = RpcWritable.wrap(EchoRequestProto.getDefaultInstance())
+ .readFrom(bb);
+ Assert.assertEquals(message1, actual);
+ Assert.assertEquals(0, bb.remaining());
+ }
+
+ @Test
+ public void testBufferWrapper() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(baos);
+ message1.writeDelimitedTo(dos);
+ message2.writeDelimitedTo(dos);
+ writable.write(dos);
+
+ ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
+ RpcWritable.Buffer buf = RpcWritable.Buffer.wrap(bb);
+ Assert.assertEquals(baos.size(), bb.remaining());
+ Assert.assertEquals(baos.size(), buf.remaining());
+
+ Object actual = buf.getValue(EchoRequestProto.getDefaultInstance());
+ Assert.assertEquals(message1, actual);
+ Assert.assertTrue(bb.remaining() > 0);
+ Assert.assertEquals(bb.remaining(), buf.remaining());
+
+ actual = buf.getValue(EchoRequestProto.getDefaultInstance());
+ Assert.assertEquals(message2, actual);
+ Assert.assertTrue(bb.remaining() > 0);
+ Assert.assertEquals(bb.remaining(), buf.remaining());
+
+ actual = buf.newInstance(LongWritable.class, null);
+ Assert.assertEquals(writable, actual);
+ Assert.assertEquals(0, bb.remaining());
+ Assert.assertEquals(0, buf.remaining());
+ }
+
+ @Test
+ public void testBufferWrapperNested() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(baos);
+ writable.write(dos);
+ message1.writeDelimitedTo(dos);
+ message2.writeDelimitedTo(dos);
+ ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
+ RpcWritable.Buffer buf1 = RpcWritable.Buffer.wrap(bb);
+ Assert.assertEquals(baos.size(), bb.remaining());
+ Assert.assertEquals(baos.size(), buf1.remaining());
+
+ Object actual = buf1.newInstance(LongWritable.class, null);
+ Assert.assertEquals(writable, actual);
+ int left = bb.remaining();
+ Assert.assertTrue(left > 0);
+ Assert.assertEquals(left, buf1.remaining());
+
+ // original bb now appears empty, but rpc writable has a slice of the bb.
+ RpcWritable.Buffer buf2 = buf1.newInstance(RpcWritable.Buffer.class, null);
+ Assert.assertEquals(0, bb.remaining());
+ Assert.assertEquals(0, buf1.remaining());
+ Assert.assertEquals(left, buf2.remaining());
+
+ actual = buf2.getValue(EchoRequestProto.getDefaultInstance());
+ Assert.assertEquals(message1, actual);
+ Assert.assertTrue(buf2.remaining() > 0);
+
+ actual = buf2.getValue(EchoRequestProto.getDefaultInstance());
+ Assert.assertEquals(message2, actual);
+ Assert.assertEquals(0, buf2.remaining());
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org
[4/4] hadoop git commit: HADOOP-13465. Design Server.Call to be
extensible for unified call queue. Contributed by Daryn Sharp.
Posted by ki...@apache.org.
HADOOP-13465. Design Server.Call to be extensible for unified call queue. Contributed by Daryn Sharp.
(cherry picked from commit 76cd81f4b656f0d40a4b2122e15f04ea53d8020b)
Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/2ff6b13e
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/2ff6b13e
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/2ff6b13e
Branch: refs/heads/branch-2.8
Commit: 2ff6b13e693e695a503b25050d4582418d1b31bf
Parents: a4292fe
Author: Kihwal Lee <ki...@apache.org>
Authored: Thu Sep 1 16:11:45 2016 -0500
Committer: Kihwal Lee <ki...@apache.org>
Committed: Thu Sep 1 16:11:45 2016 -0500
----------------------------------------------------------------------
.../main/java/org/apache/hadoop/ipc/Server.java | 336 +++++++++++--------
1 file changed, 191 insertions(+), 145 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hadoop/blob/2ff6b13e/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
index d7a2673c..54c7ac4 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
@@ -353,10 +353,9 @@ public abstract class Server {
*/
public static InetAddress getRemoteIp() {
Call call = CurCall.get();
- return (call != null && call.connection != null) ? call.connection
- .getHostInetAddress() : null;
+ return (call != null ) ? call.getHostInetAddress() : null;
}
-
+
/**
* Returns the clientId from the current RPC request
*/
@@ -379,10 +378,9 @@ public abstract class Server {
*/
public static UserGroupInformation getRemoteUser() {
Call call = CurCall.get();
- return (call != null && call.connection != null) ? call.connection.user
- : null;
+ return (call != null) ? call.getRemoteUser() : null;
}
-
+
/** Return true if the invocation was through an RPC.
*/
public static boolean isRpcInvocation() {
@@ -482,7 +480,7 @@ public abstract class Server {
if ((rpcMetrics.getProcessingSampleCount() > minSampleSize) &&
(processingTime > threeSigma)) {
if(LOG.isWarnEnabled()) {
- String client = CurCall.get().connection.toString();
+ String client = CurCall.get().toString();
LOG.warn(
"Slow RPC : " + methodName + " took " + processingTime +
" milliseconds to process from client " + client);
@@ -656,62 +654,65 @@ public abstract class Server {
CommonConfigurationKeys.IPC_BACKOFF_ENABLE_DEFAULT);
}
- /** A call queued for handling. */
- public static class Call implements Schedulable {
- private final int callId; // the client's call id
- private final int retryCount; // the retry count of the call
- private final Writable rpcRequest; // Serialized Rpc request from client
- private final Connection connection; // connection to client
- private long timestamp; // time received when response is null
- // time served when response is not null
- private ByteBuffer rpcResponse; // the response for this call
+ /** A generic call queued for handling. */
+ public static class Call implements Schedulable,
+ PrivilegedExceptionAction<Void> {
+ final int callId; // the client's call id
+ final int retryCount; // the retry count of the call
+ long timestamp; // time received when response is null
+ // time served when response is not null
private AtomicInteger responseWaitCount = new AtomicInteger(1);
- private final RPC.RpcKind rpcKind;
- private final byte[] clientId;
+ final RPC.RpcKind rpcKind;
+ final byte[] clientId;
private final TraceScope traceScope; // the HTrace scope on the server side
private final CallerContext callerContext; // the call context
private int priorityLevel;
// the priority level assigned by scheduler, 0 by default
- private Call(Call call) {
- this(call.callId, call.retryCount, call.rpcRequest, call.connection,
- call.rpcKind, call.clientId, call.traceScope, call.callerContext);
+ Call(Call call) {
+ this(call.callId, call.retryCount, call.rpcKind, call.clientId,
+ call.traceScope, call.callerContext);
}
- public Call(int id, int retryCount, Writable param,
- Connection connection) {
- this(id, retryCount, param, connection, RPC.RpcKind.RPC_BUILTIN,
- RpcConstants.DUMMY_CLIENT_ID);
+ Call(int id, int retryCount, RPC.RpcKind kind, byte[] clientId) {
+ this(id, retryCount, kind, clientId, null, null);
}
- public Call(int id, int retryCount, Writable param, Connection connection,
+ @VisibleForTesting // primarily TestNamenodeRetryCache
+ public Call(int id, int retryCount, Void ignore1, Void ignore2,
RPC.RpcKind kind, byte[] clientId) {
- this(id, retryCount, param, connection, kind, clientId, null, null);
+ this(id, retryCount, kind, clientId, null, null);
}
- public Call(int id, int retryCount, Writable param, Connection connection,
- RPC.RpcKind kind, byte[] clientId, TraceScope traceScope,
- CallerContext callerContext) {
+ Call(int id, int retryCount, RPC.RpcKind kind, byte[] clientId,
+ TraceScope traceScope, CallerContext callerContext) {
this.callId = id;
this.retryCount = retryCount;
- this.rpcRequest = param;
- this.connection = connection;
this.timestamp = Time.now();
- this.rpcResponse = null;
this.rpcKind = kind;
this.clientId = clientId;
this.traceScope = traceScope;
this.callerContext = callerContext;
}
-
+
@Override
public String toString() {
- return rpcRequest + " from " + connection + " Call#" + callId + " Retry#"
- + retryCount;
+ return "Call#" + callId + " Retry#" + retryCount;
}
- public void setResponse(ByteBuffer response) {
- this.rpcResponse = response;
+ public Void run() throws Exception {
+ return null;
+ }
+ // should eventually be abstract but need to avoid breaking tests
+ public UserGroupInformation getRemoteUser() {
+ return null;
+ }
+ public InetAddress getHostInetAddress() {
+ return null;
+ }
+ public String getHostAddress() {
+ InetAddress addr = getHostInetAddress();
+ return (addr != null) ? addr.getHostAddress() : null;
}
/**
@@ -723,34 +724,36 @@ public abstract class Server {
*/
@InterfaceStability.Unstable
@InterfaceAudience.LimitedPrivate({"HDFS"})
- public void postponeResponse() {
+ public final void postponeResponse() {
int count = responseWaitCount.incrementAndGet();
assert count > 0 : "response has already been sent";
}
@InterfaceStability.Unstable
@InterfaceAudience.LimitedPrivate({"HDFS"})
- public void sendResponse() throws IOException {
+ public final void sendResponse() throws IOException {
int count = responseWaitCount.decrementAndGet();
assert count >= 0 : "response has already been sent";
if (count == 0) {
- connection.sendResponse(this);
+ doResponse(null);
}
}
@InterfaceStability.Unstable
@InterfaceAudience.LimitedPrivate({"HDFS"})
- public void abortResponse(Throwable t) throws IOException {
+ public final void abortResponse(Throwable t) throws IOException {
// don't send response if the call was already sent or aborted.
if (responseWaitCount.getAndSet(-1) > 0) {
- connection.abortResponse(this, t);
+ doResponse(t);
}
}
+ void doResponse(Throwable t) throws IOException {}
+
// For Schedulable
@Override
public UserGroupInformation getUserGroupInformation() {
- return connection.user;
+ return getRemoteUser();
}
@Override
@@ -763,6 +766,114 @@ public abstract class Server {
}
}
+ /** A RPC extended call queued for handling. */
+ private class RpcCall extends Call {
+ final Connection connection; // connection to client
+ final Writable rpcRequest; // Serialized Rpc request from client
+ ByteBuffer rpcResponse; // the response for this call
+
+ RpcCall(RpcCall call) {
+ super(call);
+ this.connection = call.connection;
+ this.rpcRequest = call.rpcRequest;
+ }
+
+ RpcCall(Connection connection, int id) {
+ this(connection, id, RpcConstants.INVALID_RETRY_COUNT);
+ }
+
+ RpcCall(Connection connection, int id, int retryCount) {
+ this(connection, id, retryCount, null,
+ RPC.RpcKind.RPC_BUILTIN, RpcConstants.DUMMY_CLIENT_ID,
+ null, null);
+ }
+
+ RpcCall(Connection connection, int id, int retryCount,
+ Writable param, RPC.RpcKind kind, byte[] clientId,
+ TraceScope traceScope, CallerContext context) {
+ super(id, retryCount, kind, clientId, traceScope, context);
+ this.connection = connection;
+ this.rpcRequest = param;
+ }
+
+ @Override
+ public UserGroupInformation getRemoteUser() {
+ return connection.user;
+ }
+
+ @Override
+ public InetAddress getHostInetAddress() {
+ return connection.getHostInetAddress();
+ }
+
+ @Override
+ public Void run() throws Exception {
+ if (!connection.channel.isOpen()) {
+ Server.LOG.info(Thread.currentThread().getName() + ": skipped " + this);
+ return null;
+ }
+ String errorClass = null;
+ String error = null;
+ RpcStatusProto returnStatus = RpcStatusProto.SUCCESS;
+ RpcErrorCodeProto detailedErr = null;
+ Writable value = null;
+
+ try {
+ value = call(
+ rpcKind, connection.protocolName, rpcRequest, timestamp);
+ } catch (Throwable e) {
+ if (e instanceof UndeclaredThrowableException) {
+ e = e.getCause();
+ }
+ logException(Server.LOG, e, this);
+ if (e instanceof RpcServerException) {
+ RpcServerException rse = ((RpcServerException)e);
+ returnStatus = rse.getRpcStatusProto();
+ detailedErr = rse.getRpcErrorCodeProto();
+ } else {
+ returnStatus = RpcStatusProto.ERROR;
+ detailedErr = RpcErrorCodeProto.ERROR_APPLICATION;
+ }
+ errorClass = e.getClass().getName();
+ error = StringUtils.stringifyException(e);
+ // Remove redundant error class name from the beginning of the
+ // stack trace
+ String exceptionHdr = errorClass + ": ";
+ if (error.startsWith(exceptionHdr)) {
+ error = error.substring(exceptionHdr.length());
+ }
+ }
+ setupResponse(this, returnStatus, detailedErr,
+ value, errorClass, error);
+ sendResponse();
+ return null;
+ }
+
+ void setResponse(ByteBuffer response) throws IOException {
+ this.rpcResponse = response;
+ }
+
+ @Override
+ void doResponse(Throwable t) throws IOException {
+ RpcCall call = this;
+ if (t != null) {
+ // clone the call to prevent a race with another thread stomping
+ // on the response while being sent. the original call is
+ // effectively discarded since the wait count won't hit zero
+ call = new RpcCall(this);
+ setupResponse(call,
+ RpcStatusProto.FATAL, RpcErrorCodeProto.ERROR_RPC_SERVER,
+ null, t.getClass().getName(), StringUtils.stringifyException(t));
+ }
+ connection.sendResponse(call);
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + " " + rpcRequest + " from " + connection;
+ }
+ }
+
/** Listens on the socket. Creates jobs for the handler threads*/
private class Listener extends Thread {
@@ -1093,22 +1204,22 @@ public abstract class Server {
if(LOG.isDebugEnabled()) {
LOG.debug("Checking for old call responses.");
}
- ArrayList<Call> calls;
+ ArrayList<RpcCall> calls;
// get the list of channels from list of keys.
synchronized (writeSelector.keys()) {
- calls = new ArrayList<Call>(writeSelector.keys().size());
+ calls = new ArrayList<RpcCall>(writeSelector.keys().size());
iter = writeSelector.keys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
- Call call = (Call)key.attachment();
+ RpcCall call = (RpcCall)key.attachment();
if (call != null && key.channel() == call.connection.channel) {
calls.add(call);
}
}
}
-
- for(Call call : calls) {
+
+ for (RpcCall call : calls) {
doPurge(call, now);
}
} catch (OutOfMemoryError e) {
@@ -1126,7 +1237,7 @@ public abstract class Server {
}
private void doAsyncWrite(SelectionKey key) throws IOException {
- Call call = (Call)key.attachment();
+ RpcCall call = (RpcCall)key.attachment();
if (call == null) {
return;
}
@@ -1154,10 +1265,10 @@ public abstract class Server {
// Remove calls that have been pending in the responseQueue
// for a long time.
//
- private void doPurge(Call call, long now) {
- LinkedList<Call> responseQueue = call.connection.responseQueue;
+ private void doPurge(RpcCall call, long now) {
+ LinkedList<RpcCall> responseQueue = call.connection.responseQueue;
synchronized (responseQueue) {
- Iterator<Call> iter = responseQueue.listIterator(0);
+ Iterator<RpcCall> iter = responseQueue.listIterator(0);
while (iter.hasNext()) {
call = iter.next();
if (now > call.timestamp + PURGE_INTERVAL) {
@@ -1171,12 +1282,12 @@ public abstract class Server {
// Processes one response. Returns true if there are no more pending
// data for this channel.
//
- private boolean processResponse(LinkedList<Call> responseQueue,
+ private boolean processResponse(LinkedList<RpcCall> responseQueue,
boolean inHandler) throws IOException {
boolean error = true;
boolean done = false; // there is more data for this channel.
int numElements = 0;
- Call call = null;
+ RpcCall call = null;
try {
synchronized (responseQueue) {
//
@@ -1259,7 +1370,7 @@ public abstract class Server {
//
// Enqueue a response from the application.
//
- void doRespond(Call call) throws IOException {
+ void doRespond(RpcCall call) throws IOException {
synchronized (call.connection.responseQueue) {
// must only wrap before adding to the responseQueue to prevent
// postponed responses from being encrypted and sent out of order.
@@ -1357,7 +1468,7 @@ public abstract class Server {
private SocketChannel channel;
private ByteBuffer data;
private ByteBuffer dataLengthBuffer;
- private LinkedList<Call> responseQueue;
+ private LinkedList<RpcCall> responseQueue;
// number of outstanding rpcs
private AtomicInteger rpcCount = new AtomicInteger();
private long lastContact;
@@ -1384,8 +1495,8 @@ public abstract class Server {
public UserGroupInformation attemptingUser = null; // user name before auth
// Fake 'call' for failed authorization response
- private final Call authFailedCall = new Call(AUTHORIZATION_FAILED_CALL_ID,
- RpcConstants.INVALID_RETRY_COUNT, null, this);
+ private final RpcCall authFailedCall =
+ new RpcCall(this, AUTHORIZATION_FAILED_CALL_ID);
private boolean sentNegotiate = false;
private boolean useWrap = false;
@@ -1405,7 +1516,7 @@ public abstract class Server {
this.hostAddress = addr.getHostAddress();
}
this.remotePort = socket.getPort();
- this.responseQueue = new LinkedList<Call>();
+ this.responseQueue = new LinkedList<RpcCall>();
if (socketSendBufferSize != 0) {
try {
socket.setSendBufferSize(socketSendBufferSize);
@@ -1666,8 +1777,7 @@ public abstract class Server {
}
private void doSaslReply(Message message) throws IOException {
- final Call saslCall = new Call(AuthProtocol.SASL.callId,
- RpcConstants.INVALID_RETRY_COUNT, null, this);
+ final RpcCall saslCall = new RpcCall(this, AuthProtocol.SASL.callId);
setupResponse(saslCall,
RpcStatusProto.SUCCESS, null,
RpcWritable.wrap(message), null, null);
@@ -1853,23 +1963,20 @@ public abstract class Server {
if (clientVersion >= 9) {
// Versions >>9 understand the normal response
- Call fakeCall = new Call(-1, RpcConstants.INVALID_RETRY_COUNT, null,
- this);
+ RpcCall fakeCall = new RpcCall(this, -1);
setupResponse(fakeCall,
RpcStatusProto.FATAL, RpcErrorCodeProto.FATAL_VERSION_MISMATCH,
null, VersionMismatch.class.getName(), errMsg);
fakeCall.sendResponse();
} else if (clientVersion >= 3) {
- Call fakeCall = new Call(-1, RpcConstants.INVALID_RETRY_COUNT, null,
- this);
+ RpcCall fakeCall = new RpcCall(this, -1);
// Versions 3 to 8 use older response
setupResponseOldVersionFatal(buffer, fakeCall,
null, VersionMismatch.class.getName(), errMsg);
fakeCall.sendResponse();
} else if (clientVersion == 2) { // Hadoop 0.18.3
- Call fakeCall = new Call(0, RpcConstants.INVALID_RETRY_COUNT, null,
- this);
+ RpcCall fakeCall = new RpcCall(this, 0);
DataOutputStream out = new DataOutputStream(buffer);
out.writeInt(0); // call ID
out.writeBoolean(true); // error
@@ -1881,7 +1988,7 @@ public abstract class Server {
}
private void setupHttpRequestOnIpcPortResponse() throws IOException {
- Call fakeCall = new Call(0, RpcConstants.INVALID_RETRY_COUNT, null, this);
+ RpcCall fakeCall = new RpcCall(this, 0);
fakeCall.setResponse(ByteBuffer.wrap(
RECEIVED_HTTP_REQ_RESPONSE.getBytes(StandardCharsets.UTF_8)));
fakeCall.sendResponse();
@@ -2018,7 +2125,7 @@ public abstract class Server {
}
} catch (WrappedRpcServerException wrse) { // inform client of error
Throwable ioe = wrse.getCause();
- final Call call = new Call(callId, retry, null, this);
+ final RpcCall call = new RpcCall(this, callId, retry);
setupResponse(call,
RpcStatusProto.FATAL, wrse.getRpcErrorCodeProto(), null,
ioe.getClass().getName(), ioe.getMessage());
@@ -2115,8 +2222,9 @@ public abstract class Server {
.build();
}
- Call call = new Call(header.getCallId(), header.getRetryCount(),
- rpcRequest, this, ProtoUtil.convert(header.getRpcKind()),
+ RpcCall call = new RpcCall(this, header.getCallId(),
+ header.getRetryCount(), rpcRequest,
+ ProtoUtil.convert(header.getRpcKind()),
header.getClientId().toByteArray(), traceScope, callerContext);
// Save the priority level assignment by the scheduler
@@ -2239,21 +2347,10 @@ public abstract class Server {
}
}
- private void sendResponse(Call call) throws IOException {
+ private void sendResponse(RpcCall call) throws IOException {
responder.doRespond(call);
}
- private void abortResponse(Call call, Throwable t) throws IOException {
- // clone the call to prevent a race with the other thread stomping
- // on the response while being sent. the original call is
- // effectively discarded since the wait count won't hit zero
- call = new Call(call);
- setupResponse(call,
- RpcStatusProto.FATAL, RpcErrorCodeProto.ERROR_RPC_SERVER,
- null, t.getClass().getName(), StringUtils.stringifyException(t));
- call.sendResponse();
- }
-
/**
* Get service class for connection
* @return the serviceClass
@@ -2304,16 +2401,6 @@ public abstract class Server {
if (LOG.isDebugEnabled()) {
LOG.debug(Thread.currentThread().getName() + ": " + call + " for RpcKind " + call.rpcKind);
}
- if (!call.connection.channel.isOpen()) {
- LOG.info(Thread.currentThread().getName() + ": skipped " + call);
- continue;
- }
- String errorClass = null;
- String error = null;
- RpcStatusProto returnStatus = RpcStatusProto.SUCCESS;
- RpcErrorCodeProto detailedErr = null;
- Writable value = null;
-
CurCall.set(call);
if (call.traceScope != null) {
call.traceScope.reattach();
@@ -2322,53 +2409,11 @@ public abstract class Server {
}
// always update the current call context
CallerContext.setCurrent(call.callerContext);
-
- try {
- // Make the call as the user via Subject.doAs, thus associating
- // the call with the Subject
- if (call.connection.user == null) {
- value = call(call.rpcKind, call.connection.protocolName, call.rpcRequest,
- call.timestamp);
- } else {
- value =
- call.connection.user.doAs
- (new PrivilegedExceptionAction<Writable>() {
- @Override
- public Writable run() throws Exception {
- // make the call
- return call(call.rpcKind, call.connection.protocolName,
- call.rpcRequest, call.timestamp);
-
- }
- }
- );
- }
- } catch (Throwable e) {
- if (e instanceof UndeclaredThrowableException) {
- e = e.getCause();
- }
- logException(LOG, e, call);
- if (e instanceof RpcServerException) {
- RpcServerException rse = ((RpcServerException)e);
- returnStatus = rse.getRpcStatusProto();
- detailedErr = rse.getRpcErrorCodeProto();
- } else {
- returnStatus = RpcStatusProto.ERROR;
- detailedErr = RpcErrorCodeProto.ERROR_APPLICATION;
- }
- errorClass = e.getClass().getName();
- error = StringUtils.stringifyException(e);
- // Remove redundant error class name from the beginning of the stack trace
- String exceptionHdr = errorClass + ": ";
- if (error.startsWith(exceptionHdr)) {
- error = error.substring(exceptionHdr.length());
- }
- }
- CurCall.set(null);
- synchronized (call.connection.responseQueue) {
- setupResponse(call, returnStatus, detailedErr,
- value, errorClass, error);
- call.sendResponse();
+ UserGroupInformation remoteUser = call.getRemoteUser();
+ if (remoteUser != null) {
+ remoteUser.doAs(call);
+ } else {
+ call.run();
}
} catch (InterruptedException e) {
if (running) { // unexpected -- log it
@@ -2385,6 +2430,7 @@ public abstract class Server {
StringUtils.stringifyException(e));
}
} finally {
+ CurCall.set(null);
IOUtils.cleanup(LOG, traceScope);
}
}
@@ -2586,7 +2632,7 @@ public abstract class Server {
* @throws IOException
*/
private void setupResponse(
- Call call, RpcStatusProto status, RpcErrorCodeProto erCode,
+ RpcCall call, RpcStatusProto status, RpcErrorCodeProto erCode,
Writable rv, String errorClass, String error)
throws IOException {
RpcResponseHeaderProto.Builder headerBuilder =
@@ -2620,7 +2666,7 @@ public abstract class Server {
}
}
- private void setupResponse(Call call,
+ private void setupResponse(RpcCall call,
RpcResponseHeaderProto header, Writable rv) throws IOException {
ResponseBuffer buf = responseBuffer.get().reset();
try {
@@ -2654,7 +2700,7 @@ public abstract class Server {
* @throws IOException
*/
private void setupResponseOldVersionFatal(ByteArrayOutputStream response,
- Call call,
+ RpcCall call,
Writable rv, String errorClass, String error)
throws IOException {
final int OLD_VERSION_FATAL_STATUS = -1;
@@ -2667,7 +2713,7 @@ public abstract class Server {
call.setResponse(ByteBuffer.wrap(response.toByteArray()));
}
- private void wrapWithSasl(Call call) throws IOException {
+ private void wrapWithSasl(RpcCall call) throws IOException {
if (call.connection.saslServer != null) {
byte[] token = call.rpcResponse.array();
// synchronization may be needed since there can be multiple Handler
---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org