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