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.protobuf;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.List;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.Cell;
27  import org.apache.hadoop.hbase.CellScanner;
28  import org.apache.hadoop.hbase.DoNotRetryIOException;
29  import org.apache.hadoop.hbase.HRegionInfo;
30  import org.apache.hadoop.hbase.ServerName;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.client.Result;
33  import org.apache.hadoop.hbase.ipc.ServerRpcController;
34  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.GetUserPermissionsResponse;
35  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
36  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
37  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoResponse;
38  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionResponse;
39  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
40  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
41  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiRequest;
42  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse;
43  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionAction;
44  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionActionResult;
45  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ResultOrException;
46  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
47  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
48  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPair;
49  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableCatalogJanitorResponse;
50  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RunCatalogScanResponse;
51  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.GetLastFlushedSequenceIdResponse;
52  import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
53  import org.apache.hadoop.hbase.security.access.UserPermission;
54  import org.apache.hadoop.util.StringUtils;
55  
56  import com.google.protobuf.ByteString;
57  import com.google.protobuf.RpcController;
58  
59  /**
60   * Helper utility to build protocol buffer responses,
61   * or retrieve data from protocol buffer responses.
62   */
63  @InterfaceAudience.Private
64  public final class ResponseConverter {
65    public static final Log LOG = LogFactory.getLog(ResponseConverter.class);
66  
67    private ResponseConverter() {
68    }
69  
70  // Start utilities for Client
71  
72    /**
73     * Get the results from a protocol buffer MultiResponse
74     *
75     * @param request the protocol buffer MultiResponse to convert
76     * @param cells Cells to go with the passed in <code>proto</code>.  Can be null.
77     * @return the results that were in the MultiResponse (a Result or an Exception).
78     * @throws IOException
79     */
80    public static org.apache.hadoop.hbase.client.MultiResponse getResults(final MultiRequest request,
81        final MultiResponse response, final CellScanner cells)
82    throws IOException {
83      int requestRegionActionCount = request.getRegionActionCount();
84      int responseRegionActionResultCount = response.getRegionActionResultCount();
85      if (requestRegionActionCount != responseRegionActionResultCount) {
86        throw new IllegalStateException("Request mutation count=" + responseRegionActionResultCount +
87            " does not match response mutation result count=" + responseRegionActionResultCount);
88      }
89  
90      org.apache.hadoop.hbase.client.MultiResponse results =
91        new org.apache.hadoop.hbase.client.MultiResponse();
92  
93      for (int i = 0; i < responseRegionActionResultCount; i++) {
94        RegionAction actions = request.getRegionAction(i);
95        RegionActionResult actionResult = response.getRegionActionResult(i);
96        HBaseProtos.RegionSpecifier rs = actions.getRegion();
97        if (rs.hasType() &&
98            (rs.getType() != HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME)){
99          throw new IllegalArgumentException(
100             "We support only encoded types for protobuf multi response.");
101       }
102       byte[] regionName = rs.getValue().toByteArray();
103 
104       if (actionResult.hasException()) {
105         Throwable regionException =  ProtobufUtil.toException(actionResult.getException());
106         results.addException(regionName, regionException);
107         continue;
108       }
109 
110       if (actions.getActionCount() != actionResult.getResultOrExceptionCount()) {
111         throw new IllegalStateException("actions.getActionCount=" + actions.getActionCount() +
112             ", actionResult.getResultOrExceptionCount=" +
113             actionResult.getResultOrExceptionCount() + " for region " + actions.getRegion());
114       }
115 
116       for (ResultOrException roe : actionResult.getResultOrExceptionList()) {
117         if (roe.hasException()) {
118           results.add(regionName, roe.getIndex(), ProtobufUtil.toException(roe.getException()));
119         } else if (roe.hasResult()) {
120           results.add(regionName, roe.getIndex(), ProtobufUtil.toResult(roe.getResult(), cells));
121         } else if (roe.hasServiceResult()) {
122           results.add(regionName, roe.getIndex(), roe.getServiceResult());
123         } else {
124           // no result & no exception. Unexpected.
125           throw new IllegalStateException("No result & no exception roe=" + roe +
126               " for region " + actions.getRegion());
127         }
128       }
129     }
130 
131     return results;
132   }
133 
134   /**
135    * Wrap a throwable to an action result.
136    *
137    * @param t
138    * @return an action result builder
139    */
140   public static ResultOrException.Builder buildActionResult(final Throwable t) {
141     ResultOrException.Builder builder = ResultOrException.newBuilder();
142     if (t != null) builder.setException(buildException(t));
143     return builder;
144   }
145 
146   /**
147    * Wrap a throwable to an action result.
148    *
149    * @param r
150    * @return an action result builder
151    */
152   public static ResultOrException.Builder buildActionResult(final ClientProtos.Result r) {
153     ResultOrException.Builder builder = ResultOrException.newBuilder();
154     if (r != null) builder.setResult(r);
155     return builder;
156   }
157 
158   /**
159    * @param t
160    * @return NameValuePair of the exception name to stringified version os exception.
161    */
162   public static NameBytesPair buildException(final Throwable t) {
163     NameBytesPair.Builder parameterBuilder = NameBytesPair.newBuilder();
164     parameterBuilder.setName(t.getClass().getName());
165     parameterBuilder.setValue(
166       ByteString.copyFromUtf8(StringUtils.stringifyException(t)));
167     return parameterBuilder.build();
168   }
169 
170   /**
171    * Converts the permissions list into a protocol buffer GetUserPermissionsResponse
172    */
173   public static GetUserPermissionsResponse buildGetUserPermissionsResponse(
174       final List<UserPermission> permissions) {
175     GetUserPermissionsResponse.Builder builder = GetUserPermissionsResponse.newBuilder();
176     for (UserPermission perm : permissions) {
177       builder.addUserPermission(ProtobufUtil.toUserPermission(perm));
178     }
179     return builder.build();
180   }
181 
182 // End utilities for Client
183 // Start utilities for Admin
184 
185   /**
186    * Get the list of region info from a GetOnlineRegionResponse
187    *
188    * @param proto the GetOnlineRegionResponse
189    * @return the list of region info
190    */
191   public static List<HRegionInfo> getRegionInfos(final GetOnlineRegionResponse proto) {
192     if (proto == null || proto.getRegionInfoCount() == 0) return null;
193     return ProtobufUtil.getRegionInfos(proto);
194   }
195 
196   /**
197    * Get the region opening state from a OpenRegionResponse
198    *
199    * @param proto the OpenRegionResponse
200    * @return the region opening state
201    */
202   public static RegionOpeningState getRegionOpeningState
203       (final OpenRegionResponse proto) {
204     if (proto == null || proto.getOpeningStateCount() != 1) return null;
205     return RegionOpeningState.valueOf(
206       proto.getOpeningState(0).name());
207   }
208 
209   /**
210    * Get a list of region opening state from a OpenRegionResponse
211    * 
212    * @param proto the OpenRegionResponse
213    * @return the list of region opening state
214    */
215   public static List<RegionOpeningState> getRegionOpeningStateList(
216       final OpenRegionResponse proto) {
217     if (proto == null) return null;
218     List<RegionOpeningState> regionOpeningStates = new ArrayList<RegionOpeningState>();
219     for (int i = 0; i < proto.getOpeningStateCount(); i++) {
220       regionOpeningStates.add(RegionOpeningState.valueOf(
221           proto.getOpeningState(i).name()));
222     }
223     return regionOpeningStates;
224   }
225 
226   /**
227    * Check if the region is closed from a CloseRegionResponse
228    *
229    * @param proto the CloseRegionResponse
230    * @return the region close state
231    */
232   public static boolean isClosed
233       (final CloseRegionResponse proto) {
234     if (proto == null || !proto.hasClosed()) return false;
235     return proto.getClosed();
236   }
237 
238   /**
239    * A utility to build a GetServerInfoResponse.
240    *
241    * @param serverName
242    * @param webuiPort
243    * @return the response
244    */
245   public static GetServerInfoResponse buildGetServerInfoResponse(
246       final ServerName serverName, final int webuiPort) {
247     GetServerInfoResponse.Builder builder = GetServerInfoResponse.newBuilder();
248     ServerInfo.Builder serverInfoBuilder = ServerInfo.newBuilder();
249     serverInfoBuilder.setServerName(ProtobufUtil.toServerName(serverName));
250     if (webuiPort >= 0) {
251       serverInfoBuilder.setWebuiPort(webuiPort);
252     }
253     builder.setServerInfo(serverInfoBuilder.build());
254     return builder.build();
255   }
256 
257   /**
258    * A utility to build a GetOnlineRegionResponse.
259    *
260    * @param regions
261    * @return the response
262    */
263   public static GetOnlineRegionResponse buildGetOnlineRegionResponse(
264       final List<HRegionInfo> regions) {
265     GetOnlineRegionResponse.Builder builder = GetOnlineRegionResponse.newBuilder();
266     for (HRegionInfo region: regions) {
267       builder.addRegionInfo(HRegionInfo.convert(region));
268     }
269     return builder.build();
270   }
271 
272   /**
273    * Creates a response for the catalog scan request
274    * @return A RunCatalogScanResponse
275    */
276   public static RunCatalogScanResponse buildRunCatalogScanResponse(int numCleaned) {
277     return RunCatalogScanResponse.newBuilder().setScanResult(numCleaned).build();
278   }
279 
280   /**
281    * Creates a response for the catalog scan request
282    * @return A EnableCatalogJanitorResponse
283    */
284   public static EnableCatalogJanitorResponse buildEnableCatalogJanitorResponse(boolean prevValue) {
285     return EnableCatalogJanitorResponse.newBuilder().setPrevValue(prevValue).build();
286   }
287 
288 // End utilities for Admin
289 
290   /**
291    * Creates a response for the last flushed sequence Id request
292    * @return A GetLastFlushedSequenceIdResponse
293    */
294   public static GetLastFlushedSequenceIdResponse buildGetLastFlushedSequenceIdResponse(
295       long seqId) {
296     return GetLastFlushedSequenceIdResponse.newBuilder().setLastFlushedSequenceId(seqId).build();
297   }
298 
299   /**
300    * Stores an exception encountered during RPC invocation so it can be passed back
301    * through to the client.
302    * @param controller the controller instance provided by the client when calling the service
303    * @param ioe the exception encountered
304    */
305   public static void setControllerException(RpcController controller, IOException ioe) {
306     if (controller != null) {
307       if (controller instanceof ServerRpcController) {
308         ((ServerRpcController)controller).setFailedOn(ioe);
309       } else {
310         controller.setFailed(StringUtils.stringifyException(ioe));
311       }
312     }
313   }
314 
315   /**
316    * Create Results from the cells using the cells meta data. 
317    * @param cellScanner
318    * @param response
319    * @return results
320    */
321   public static Result[] getResults(CellScanner cellScanner, ScanResponse response)
322       throws IOException {
323     if (response == null) return null;
324     // If cellscanner, then the number of Results to return is the count of elements in the
325     // cellsPerResult list.  Otherwise, it is how many results are embedded inside the response.
326     int noOfResults = cellScanner != null?
327       response.getCellsPerResultCount(): response.getResultsCount();
328     Result[] results = new Result[noOfResults];
329     for (int i = 0; i < noOfResults; i++) {
330       if (cellScanner != null) {
331         // Cells are out in cellblocks.  Group them up again as Results.  How many to read at a
332         // time will be found in getCellsLength -- length here is how many Cells in the i'th Result
333         int noOfCells = response.getCellsPerResult(i);
334         List<Cell> cells = new ArrayList<Cell>(noOfCells);
335         for (int j = 0; j < noOfCells; j++) {
336           try {
337             if (cellScanner.advance() == false) {
338               // We are not able to retrieve the exact number of cells which ResultCellMeta says us.
339               // We have to scan for the same results again. Throwing DNRIOE as a client retry on the
340               // same scanner will result in OutOfOrderScannerNextException
341               String msg = "Results sent from server=" + noOfResults + ". But only got " + i
342                 + " results completely at client. Resetting the scanner to scan again.";
343               LOG.error(msg);
344               throw new DoNotRetryIOException(msg);
345             }
346           } catch (IOException ioe) {
347             // We are getting IOE while retrieving the cells for Results.
348             // We have to scan for the same results again. Throwing DNRIOE as a client retry on the
349             // same scanner will result in OutOfOrderScannerNextException
350             LOG.error("Exception while reading cells from result."
351               + "Resetting the scanner to scan again.", ioe);
352             throw new DoNotRetryIOException("Resetting the scanner.", ioe);
353           }
354           cells.add(cellScanner.current());
355         }
356         results[i] = Result.create(cells, null, response.getStale());
357       } else {
358         // Result is pure pb.
359         results[i] = ProtobufUtil.toResult(response.getResults(i));
360       }
361     }
362     return results;
363   }
364 }