View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.ipc;
19  
20  import com.google.common.base.Preconditions;
21  import com.google.protobuf.CodedOutputStream;
22  import com.google.protobuf.Message;
23  import java.io.IOException;
24  import java.io.OutputStream;
25  import java.nio.BufferOverflowException;
26  import java.nio.ByteBuffer;
27  import org.apache.commons.io.IOUtils;
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.conf.Configurable;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.hbase.CellScanner;
33  import org.apache.hadoop.hbase.DoNotRetryIOException;
34  import org.apache.hadoop.hbase.HBaseIOException;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.codec.Codec;
37  import org.apache.hadoop.hbase.io.ByteBufferInputStream;
38  import org.apache.hadoop.hbase.io.ByteBufferOutputStream;
39  import org.apache.hadoop.hbase.io.ByteBufferPool;
40  import org.apache.hadoop.hbase.io.ByteBufferListOutputStream;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.hbase.util.ClassSize;
43  import org.apache.hadoop.io.compress.CodecPool;
44  import org.apache.hadoop.io.compress.CompressionCodec;
45  import org.apache.hadoop.io.compress.CompressionInputStream;
46  import org.apache.hadoop.io.compress.Compressor;
47  import org.apache.hadoop.io.compress.Decompressor;
48
49  /**
50   * Utility to help ipc'ing.
51   */
52  @InterfaceAudience.Private
53  public class IPCUtil {
54    // LOG is being used in TestIPCUtil
55    public static final Log LOG = LogFactory.getLog(IPCUtil.class);
56    /**
57     * How much we think the decompressor will expand the original compressed content.
58     */
59    private final int cellBlockDecompressionMultiplier;
60    private final int cellBlockBuildingInitialBufferSize;
61    private final Configuration conf;
62
63    public IPCUtil(final Configuration conf) {
64      super();
65      this.conf = conf;
66      this.cellBlockDecompressionMultiplier =
67          conf.getInt("hbase.ipc.cellblock.decompression.buffersize.multiplier", 3);
68
69      // Guess that 16k is a good size for rpc buffer.  Could go bigger.  See the TODO below in
70      // #buildCellBlock.
71      this.cellBlockBuildingInitialBufferSize =
72        ClassSize.align(conf.getInt("hbase.ipc.cellblock.building.initial.buffersize", 16 * 1024));
73    }
74
75    /**
76     * Thrown if a cellscanner but no codec to encode it with.
77     */
78    public static class CellScannerButNoCodecException extends HBaseIOException {};
79
80    /**
81     * Puts CellScanner Cells into a cell block using passed in <code>codec</code> and/or
82     * <code>compressor</code>.
83     * @param codec to use for encoding
84     * @param compressor to use for encoding
85     * @param cellScanner to encode
86     * @return Null or byte buffer filled with a cellblock filled with passed-in Cells encoded using
87     *   passed in <code>codec</code> and/or <code>compressor</code>; the returned buffer has been
88     *   flipped and is ready for reading.  Use limit to find total size.
89     * @throws IOException if encoding the cells fail
90     */
91    @SuppressWarnings("resource")
92    public ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor,
93        final CellScanner cellScanner) throws IOException {
94      if (cellScanner == null) {
95        return null;
96      }
97      if (codec == null) {
98        throw new CellScannerButNoCodecException();
99      }
100     int bufferSize = this.cellBlockBuildingInitialBufferSize;
101     ByteBufferOutputStream baos = new ByteBufferOutputStream(bufferSize);
102     encodeCellsTo(baos, cellScanner, codec, compressor);
103     if (LOG.isTraceEnabled()) {
104       if (bufferSize < baos.size()) {
105         LOG.trace("Buffer grew from initial bufferSize=" + bufferSize + " to " + baos.size()
106             + "; up hbase.ipc.cellblock.building.initial.buffersize?");
107       }
108     }
109     ByteBuffer bb = baos.getByteBuffer();
110     // If no cells, don't mess around. Just return null (could be a bunch of existence checking
111     // gets or something -- stuff that does not return a cell).
112     if (!bb.hasRemaining()) return null;
113     return bb;
114   }
115
116   private void encodeCellsTo(ByteBufferOutputStream bbos, CellScanner cellScanner, Codec codec,
117       CompressionCodec compressor) throws IOException {
118     OutputStream os = bbos;
119     Compressor poolCompressor = null;
120     try  {
121       if (compressor != null) {
122         if (compressor instanceof Configurable) {
123           ((Configurable) compressor).setConf(this.conf);
124         }
125         poolCompressor = CodecPool.getCompressor(compressor);
126         os = compressor.createOutputStream(os, poolCompressor);
127       }
128       Codec.Encoder encoder = codec.getEncoder(os);
129       while (cellScanner.advance()) {
130         encoder.write(cellScanner.current());
131       }
132       encoder.flush();
133     } catch (BufferOverflowException e) {
134       throw new DoNotRetryIOException(e);
135     } finally {
136       os.close();
137       if (poolCompressor != null) {
138         CodecPool.returnCompressor(poolCompressor);
139       }
140     }
141   }
142
143   /**
144    * Puts CellScanner Cells into a cell block using passed in <code>codec</code> and/or
145    * <code>compressor</code>.
146    * @param codec to use for encoding
147    * @param compressor to use for encoding
148    * @param cellScanner to encode
149    * @param pool Pool of ByteBuffers to make use of.
150    * @return Null or byte buffer filled with a cellblock filled with passed-in Cells encoded using
151    *   passed in <code>codec</code> and/or <code>compressor</code>; the returned buffer has been
152    *   flipped and is ready for reading.  Use limit to find total size. If <code>pool</code> was not
153    *   null, then this returned ByteBuffer came from there and should be returned to the pool when
154    *   done.
155    * @throws IOException if encoding the cells fail
156    */
157   @SuppressWarnings("resource")
158   public ByteBufferListOutputStream buildCellBlockStream(Codec codec, CompressionCodec compressor,
159       CellScanner cellScanner, ByteBufferPool pool) throws IOException {
160     if (cellScanner == null) {
161       return null;
162     }
163     if (codec == null) {
164       throw new CellScannerButNoCodecException();
165     }
166     assert pool != null;
167     ByteBufferListOutputStream bbos = new ByteBufferListOutputStream(pool);
168     encodeCellsTo(bbos, cellScanner, codec, compressor);
169     if (bbos.size() == 0) {
170       bbos.releaseResources();
171       return null;
172     }
173     return bbos;
174   }
175
176   /**
177    * @param codec to use for cellblock
178    * @param cellBlock to encode
179    * @return CellScanner to work against the content of <code>cellBlock</code>
180    * @throws IOException if encoding fails
181    */
182   public CellScanner createCellScanner(final Codec codec, final CompressionCodec compressor,
183       final byte[] cellBlock) throws IOException {
184     // Use this method from Client side to create the CellScanner
185     ByteBuffer cellBlockBuf = ByteBuffer.wrap(cellBlock);
186     if (compressor != null) {
187       cellBlockBuf = decompress(compressor, cellBlockBuf);
188     }
189     // Not making the Decoder over the ByteBuffer purposefully. The Decoder over the BB will
190     // make Cells directly over the passed BB. This method is called at client side and we don't
191     // want the Cells to share the same byte[] where the RPC response is being read. Caching of any
192     // of the Cells at user's app level will make it not possible to GC the response byte[]
193     return codec.getDecoder(new ByteBufferInputStream(cellBlockBuf));
194   }
195
196   /**
197    * @param codec to use for cellblock
198    * @param cellBlock ByteBuffer containing the cells written by the Codec. The buffer should be
199    *   position()'ed at the start of the cell block and limit()'ed at the end.
200    * @return CellScanner to work against the content of <code>cellBlock</code>.
201    *   All cells created out of the CellScanner will share the same ByteBuffer being passed.
202    * @throws IOException if cell encoding fails
203    */
204   public CellScanner createCellScannerReusingBuffers(final Codec codec,
205       final CompressionCodec compressor, ByteBuffer cellBlock) throws IOException {
206     // Use this method from HRS to create the CellScanner
207     // If compressed, decompress it first before passing it on else we will leak compression
208     // resources if the stream is not closed properly after we let it out.
209     if (compressor != null) {
210       cellBlock = decompress(compressor, cellBlock);
211     }
212     return codec.getDecoder(cellBlock);
213   }
214
215   private ByteBuffer decompress(CompressionCodec compressor, ByteBuffer cellBlock)
216       throws IOException {
217     // GZIPCodec fails w/ NPE if no configuration.
218     if (compressor instanceof Configurable) {
219       ((Configurable) compressor).setConf(this.conf);
220     }
221     Decompressor poolDecompressor = CodecPool.getDecompressor(compressor);
222     CompressionInputStream cis = compressor.createInputStream(new ByteBufferInputStream(cellBlock),
223         poolDecompressor);
224     ByteBufferOutputStream bbos;
225     try {
226       // TODO: This is ugly. The buffer will be resized on us if we guess wrong.
227       // TODO: Reuse buffers.
228       bbos = new ByteBufferOutputStream(
229           cellBlock.remaining() * this.cellBlockDecompressionMultiplier);
230       IOUtils.copy(cis, bbos);
231       bbos.close();
232       cellBlock = bbos.getByteBuffer();
233     } finally {
234       CodecPool.returnDecompressor(poolDecompressor);
235     }
236     return cellBlock;
237   }
238
239   /**
240    * Write out header, param, and cell block if there is one.
241    * @param dos Stream to write into
242    * @param header to write
243    * @param param to write
244    * @param cellBlock to write
245    * @return Total number of bytes written.
246    * @throws IOException if write action fails
247    */
248   public static int write(final OutputStream dos, final Message header, final Message param,
249       final ByteBuffer cellBlock)
250   throws IOException {
251     // Must calculate total size and write that first so other side can read it all in in one
252     // swoop.  This is dictated by how the server is currently written.  Server needs to change
253     // if we are to be able to write without the length prefixing.
254     int totalSize = IPCUtil.getTotalSizeWhenWrittenDelimited(header, param);
255     if (cellBlock != null) {
256       totalSize += cellBlock.remaining();
257     }
258     return write(dos, header, param, cellBlock, totalSize);
259   }
260
261   private static int write(final OutputStream dos, final Message header, final Message param,
262     final ByteBuffer cellBlock, final int totalSize)
263   throws IOException {
264     // I confirmed toBytes does same as DataOutputStream#writeInt.
265     dos.write(Bytes.toBytes(totalSize));
266     // This allocates a buffer that is the size of the message internally.
267     header.writeDelimitedTo(dos);
268     if (param != null) {
269       param.writeDelimitedTo(dos);
270     }
271     if (cellBlock != null) {
272       dos.write(cellBlock.array(), 0, cellBlock.remaining());
273     }
274     dos.flush();
275     return totalSize;
276   }
277
278   /**
279    * @return Size on the wire when the two messages are written with writeDelimitedTo
280    */
281   public static int getTotalSizeWhenWrittenDelimited(Message ... messages) {
282     int totalSize = 0;
283     for (Message m: messages) {
284       if (m == null) {
285         continue;
286       }
287       totalSize += m.getSerializedSize();
288       totalSize += CodedOutputStream.computeRawVarint32Size(m.getSerializedSize());
289     }
290     Preconditions.checkArgument(totalSize < Integer.MAX_VALUE);
291     return totalSize;
292   }
293 }