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