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 java.io.ByteArrayInputStream;
21  import java.io.DataInput;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.nio.ByteBuffer;
26  
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.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.conf.Configurable;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.CellScanner;
34  import org.apache.hadoop.hbase.HBaseIOException;
35  import org.apache.hadoop.hbase.codec.Codec;
36  import org.apache.hadoop.hbase.io.BoundedByteBufferPool;
37  import org.apache.hadoop.hbase.io.ByteBufferOutputStream;
38  import org.apache.hadoop.hbase.io.HeapSize;
39  import org.apache.hadoop.hbase.util.Bytes;
40  import org.apache.hadoop.hbase.util.ClassSize;
41  import org.apache.hadoop.io.compress.CodecPool;
42  import org.apache.hadoop.io.compress.CompressionCodec;
43  import org.apache.hadoop.io.compress.CompressionInputStream;
44  import org.apache.hadoop.io.compress.Compressor;
45  import org.apache.hadoop.io.compress.Decompressor;
46  
47  import com.google.common.base.Preconditions;
48  import com.google.protobuf.CodedOutputStream;
49  import com.google.protobuf.Message;
50  
51  /**
52   * Utility to help ipc'ing.
53   */
54  @InterfaceAudience.Private
55  public class IPCUtil {
56    public static final Log LOG = LogFactory.getLog(IPCUtil.class);
57    /**
58     * How much we think the decompressor will expand the original compressed content.
59     */
60    private final int cellBlockDecompressionMultiplier;
61    private final int cellBlockBuildingInitialBufferSize;
62    private final Configuration conf;
63  
64    public IPCUtil(final Configuration conf) {
65      super();
66      this.conf = conf;
67      this.cellBlockDecompressionMultiplier =
68          conf.getInt("hbase.ipc.cellblock.decompression.buffersize.multiplier", 3);
69  
70      // Guess that 16k is a good size for rpc buffer.  Could go bigger.  See the TODO below in
71      // #buildCellBlock.
72      this.cellBlockBuildingInitialBufferSize =
73        ClassSize.align(conf.getInt("hbase.ipc.cellblock.building.initial.buffersize", 16 * 1024));
74    }
75  
76    /**
77     * Thrown if a cellscanner but no codec to encode it with.
78     */
79    public static class CellScannerButNoCodecException extends HBaseIOException {};
80  
81    /**
82     * Puts CellScanner Cells into a cell block using passed in <code>codec</code> and/or
83     * <code>compressor</code>.
84     * @param codec
85     * @param compressor
86     * @param cellScanner
87     * @return Null or byte buffer filled with a cellblock filled with passed-in Cells encoded using
88     * passed in <code>codec</code> and/or <code>compressor</code>; the returned buffer has been
89     * flipped and is ready for reading.  Use limit to find total size.
90     * @throws IOException
91     */
92    @SuppressWarnings("resource")
93    public ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor,
94      final CellScanner cellScanner)
95    throws IOException {
96      return buildCellBlock(codec, compressor, cellScanner, null);
97    }
98  
99    /**
100    * Puts CellScanner Cells into a cell block using passed in <code>codec</code> and/or
101    * <code>compressor</code>.
102    * @param codec
103    * @param compressor
104    * @param cellScanner
105    * @param pool Pool of ByteBuffers to make use of. Can be null and then we'll allocate
106    * our own ByteBuffer.
107    * @return Null or byte buffer filled with a cellblock filled with passed-in Cells encoded using
108    * passed in <code>codec</code> and/or <code>compressor</code>; the returned buffer has been
109    * flipped and is ready for reading.  Use limit to find total size. If <code>pool</code> was not
110    * null, then this returned ByteBuffer came from there and should be returned to the pool when
111    * done.
112    * @throws IOException
113    */
114   @SuppressWarnings("resource")
115   public ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor,
116     final CellScanner cellScanner, final BoundedByteBufferPool pool)
117   throws IOException {
118     if (cellScanner == null) return null;
119     if (codec == null) throw new CellScannerButNoCodecException();
120     int bufferSize = this.cellBlockBuildingInitialBufferSize;
121     ByteBufferOutputStream baos = null;
122     if (pool != null) {
123       ByteBuffer bb = pool.getBuffer();
124       bufferSize = bb.capacity();
125       baos = new ByteBufferOutputStream(bb);
126     } else {
127       // Then we need to make our own to return.
128       if (cellScanner instanceof HeapSize) {
129         long longSize = ((HeapSize)cellScanner).heapSize();
130         // Just make sure we don't have a size bigger than an int.
131         if (longSize > Integer.MAX_VALUE) {
132           throw new IOException("Size " + longSize + " > " + Integer.MAX_VALUE);
133         }
134         bufferSize = ClassSize.align((int)longSize);
135       }
136       baos = new ByteBufferOutputStream(bufferSize);
137     }
138     OutputStream os = baos;
139     Compressor poolCompressor = null;
140     try {
141       if (compressor != null) {
142         if (compressor instanceof Configurable) ((Configurable)compressor).setConf(this.conf);
143         poolCompressor = CodecPool.getCompressor(compressor);
144         os = compressor.createOutputStream(os, poolCompressor);
145       }
146       Codec.Encoder encoder = codec.getEncoder(os);
147       int count = 0;
148       while (cellScanner.advance()) {
149         encoder.write(cellScanner.current());
150         count++;
151       }
152       encoder.flush();
153       // If no cells, don't mess around.  Just return null (could be a bunch of existence checking
154       // gets or something -- stuff that does not return a cell).
155       if (count == 0) return null;
156     } finally {
157       os.close();
158       if (poolCompressor != null) CodecPool.returnCompressor(poolCompressor);
159     }
160     if (LOG.isTraceEnabled()) {
161       if (bufferSize < baos.size()) {
162         LOG.trace("Buffer grew from initial bufferSize=" + bufferSize + " to " + baos.size() +
163           "; up hbase.ipc.cellblock.building.initial.buffersize?");
164       }
165     }
166     return baos.getByteBuffer();
167   }
168 
169   /**
170    * @param codec
171    * @param cellBlock
172    * @return CellScanner to work against the content of <code>cellBlock</code>
173    * @throws IOException
174    */
175   public CellScanner createCellScanner(final Codec codec, final CompressionCodec compressor,
176       final byte [] cellBlock)
177   throws IOException {
178     return createCellScanner(codec, compressor, cellBlock, 0, cellBlock.length);
179   }
180 
181   /**
182    * @param codec
183    * @param cellBlock
184    * @param offset
185    * @param length
186    * @return CellScanner to work against the content of <code>cellBlock</code>
187    * @throws IOException
188    */
189   public CellScanner createCellScanner(final Codec codec, final CompressionCodec compressor,
190       final byte [] cellBlock, final int offset, final int length)
191   throws IOException {
192     // If compressed, decompress it first before passing it on else we will leak compression
193     // resources if the stream is not closed properly after we let it out.
194     InputStream is = null;
195     if (compressor != null) {
196       // GZIPCodec fails w/ NPE if no configuration.
197       if (compressor instanceof Configurable) ((Configurable)compressor).setConf(this.conf);
198       Decompressor poolDecompressor = CodecPool.getDecompressor(compressor);
199       CompressionInputStream cis =
200         compressor.createInputStream(new ByteArrayInputStream(cellBlock, offset, length),
201         poolDecompressor);
202       ByteBufferOutputStream bbos = null;
203       try {
204         // TODO: This is ugly.  The buffer will be resized on us if we guess wrong.
205         // TODO: Reuse buffers.
206         bbos = new ByteBufferOutputStream((length - offset) *
207           this.cellBlockDecompressionMultiplier);
208         IOUtils.copy(cis, bbos);
209         bbos.close();
210         ByteBuffer bb = bbos.getByteBuffer();
211         is = new ByteArrayInputStream(bb.array(), 0, bb.limit());
212       } finally {
213         if (is != null) is.close();
214         if (bbos != null) bbos.close();
215 
216         CodecPool.returnDecompressor(poolDecompressor);
217       }
218     } else {
219       is = new ByteArrayInputStream(cellBlock, offset, length);
220     }
221     return codec.getDecoder(is);
222   }
223 
224   /**
225    * @param m Message to serialize delimited; i.e. w/ a vint of its size preceeding its
226    * serialization.
227    * @return The passed in Message serialized with delimiter.  Return null if <code>m</code> is null
228    * @throws IOException
229    */
230   public static ByteBuffer getDelimitedMessageAsByteBuffer(final Message m) throws IOException {
231     if (m == null) return null;
232     int serializedSize = m.getSerializedSize();
233     int vintSize = CodedOutputStream.computeRawVarint32Size(serializedSize);
234     byte [] buffer = new byte[serializedSize + vintSize];
235     // Passing in a byte array saves COS creating a buffer which it does when using streams.
236     CodedOutputStream cos = CodedOutputStream.newInstance(buffer);
237     // This will write out the vint preamble and the message serialized.
238     cos.writeMessageNoTag(m);
239     cos.flush();
240     cos.checkNoSpaceLeft();
241     return ByteBuffer.wrap(buffer);
242   }
243 
244   /**
245    * Write out header, param, and cell block if there is one.
246    * @param dos
247    * @param header
248    * @param param
249    * @param cellBlock
250    * @return Total number of bytes written.
251    * @throws IOException
252    */
253   public static int write(final OutputStream dos, final Message header, final Message param,
254       final ByteBuffer cellBlock)
255   throws IOException {
256     // Must calculate total size and write that first so other side can read it all in in one
257     // swoop.  This is dictated by how the server is currently written.  Server needs to change
258     // if we are to be able to write without the length prefixing.
259     int totalSize = IPCUtil.getTotalSizeWhenWrittenDelimited(header, param);
260     if (cellBlock != null) totalSize += cellBlock.remaining();
261     return write(dos, header, param, cellBlock, totalSize);
262   }
263 
264   private static int write(final OutputStream dos, final Message header, final Message param,
265     final ByteBuffer cellBlock, final int totalSize)
266   throws IOException {
267     // I confirmed toBytes does same as DataOutputStream#writeInt.
268     dos.write(Bytes.toBytes(totalSize));
269     // This allocates a buffer that is the size of the message internally.
270     header.writeDelimitedTo(dos);
271     if (param != null) param.writeDelimitedTo(dos);
272     if (cellBlock != null) dos.write(cellBlock.array(), 0, cellBlock.remaining());
273     dos.flush();
274     return totalSize;
275   }
276 
277   /**
278    * Read in chunks of 8K (HBASE-7239)
279    * @param in
280    * @param dest
281    * @param offset
282    * @param len
283    * @throws IOException
284    */
285   public static void readChunked(final DataInput in, byte[] dest, int offset, int len)
286       throws IOException {
287     int maxRead = 8192;
288 
289     for (; offset < len; offset += maxRead) {
290       in.readFully(dest, offset, Math.min(len - offset, maxRead));
291     }
292   }
293 
294   /**
295    * @return Size on the wire when the two messages are written with writeDelimitedTo
296    */
297   public static int getTotalSizeWhenWrittenDelimited(Message ... messages) {
298     int totalSize = 0;
299     for (Message m: messages) {
300       if (m == null) continue;
301       totalSize += m.getSerializedSize();
302       totalSize += CodedOutputStream.computeRawVarint32Size(m.getSerializedSize());
303     }
304     Preconditions.checkArgument(totalSize < Integer.MAX_VALUE);
305     return totalSize;
306   }
307 }