Java Code Examples for org.apache.hadoop.hbase.ipc.ServerRpcController

The following examples show how to use org.apache.hadoop.hbase.ipc.ServerRpcController. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: phoenix   Source File: ConnectionQueryServicesImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MetaDataMutationResult updateIndexState(final List<Mutation> tableMetaData, String parentTableName) throws SQLException {
    byte[][] rowKeyMetadata = new byte[3][];
    SchemaUtil.getVarChars(tableMetaData.get(0).getRow(), rowKeyMetadata);
    byte[] tableKey = SchemaUtil.getTableKey(ByteUtil.EMPTY_BYTE_ARRAY, rowKeyMetadata[PhoenixDatabaseMetaData.SCHEMA_NAME_INDEX], rowKeyMetadata[PhoenixDatabaseMetaData.TABLE_NAME_INDEX]);
    return metaDataCoprocessorExec(tableKey,
            new Batch.Call<MetaDataService, MetaDataResponse>() {
                @Override
                public MetaDataResponse call(MetaDataService instance) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<MetaDataResponse> rpcCallback =
                            new BlockingRpcCallback<MetaDataResponse>();
                    UpdateIndexStateRequest.Builder builder = UpdateIndexStateRequest.newBuilder();
                    for (Mutation m : tableMetaData) {
                        MutationProto mp = ProtobufUtil.toProto(m);
                        builder.addTableMetadataMutations(mp.toByteString());
                    }
                    instance.updateIndexState(controller, builder.build(), rpcCallback);
                    if(controller.getFailedOn() != null) {
                        throw controller.getFailedOn();
                    }
                    return rpcCallback.get();
                }
            });
}
 
Example 2
Source Project: phoenix   Source File: TestUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void clearMetaDataCache(Connection conn) throws Throwable {
    PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
    HTableInterface htable = pconn.getQueryServices().getTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES);
    htable.coprocessorService(MetaDataService.class, HConstants.EMPTY_START_ROW,
        HConstants.EMPTY_END_ROW, new Batch.Call<MetaDataService, ClearCacheResponse>() {
            @Override
            public ClearCacheResponse call(MetaDataService instance) throws IOException {
                ServerRpcController controller = new ServerRpcController();
                BlockingRpcCallback<ClearCacheResponse> rpcCallback =
                        new BlockingRpcCallback<ClearCacheResponse>();
                ClearCacheRequest.Builder builder = ClearCacheRequest.newBuilder();
                instance.clearCache(controller, builder.build(), rpcCallback);
                if(controller.getFailedOn() != null) {
                    throw controller.getFailedOn();
                }
                return rpcCallback.get(); 
            }
          });
}
 
Example 3
Source Project: hbase   Source File: TestRegionServerCoprocessorEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEndpoint() throws Exception {
  final ServerName serverName = TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName();
  final ServerRpcController controller = new ServerRpcController();
  final CoprocessorRpcUtils.BlockingRpcCallback<DummyRegionServerEndpointProtos.DummyResponse>
      rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>();
  DummyRegionServerEndpointProtos.DummyService service =
      ProtobufUtil.newServiceStub(DummyRegionServerEndpointProtos.DummyService.class,
        TEST_UTIL.getAdmin().coprocessorService(serverName));
  service.dummyCall(controller,
      DummyRegionServerEndpointProtos.DummyRequest.getDefaultInstance(), rpcCallback);
  assertEquals(DUMMY_VALUE, rpcCallback.get().getValue());
  if (controller.failedOnException()) {
    throw controller.getFailedOn();
  }
}
 
Example 4
Source Project: hbase   Source File: TestTokenAuthentication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationProtos.GetAuthenticationTokenResponse getAuthenticationToken(
    RpcController controller, AuthenticationProtos.GetAuthenticationTokenRequest request)
  throws ServiceException {
  LOG.debug("Authentication token request from " + RpcServer.getRequestUserName().orElse(null));
  // Ignore above passed in controller -- it is always null
  ServerRpcController serverController = new ServerRpcController();
  final BlockingRpcCallback<AuthenticationProtos.GetAuthenticationTokenResponse>
    callback = new BlockingRpcCallback<>();
  getAuthenticationToken(null, request, callback);
  try {
    serverController.checkFailed();
    return callback.get();
  } catch (IOException ioe) {
    throw new ServiceException(ioe);
  }
}
 
Example 5
Source Project: hbase   Source File: TestTokenAuthentication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationProtos.WhoAmIResponse whoAmI(
    RpcController controller, AuthenticationProtos.WhoAmIRequest request)
  throws ServiceException {
  LOG.debug("whoAmI() request from " + RpcServer.getRequestUserName().orElse(null));
  // Ignore above passed in controller -- it is always null
  ServerRpcController serverController = new ServerRpcController();
  BlockingRpcCallback<AuthenticationProtos.WhoAmIResponse> callback =
      new BlockingRpcCallback<>();
  whoAmI(null, request, callback);
  try {
    serverController.checkFailed();
    return callback.get();
  } catch (IOException ioe) {
    throw new ServiceException(ioe);
  }
}
 
Example 6
Source Project: hbase   Source File: ConnectionUtils.java    License: Apache License 2.0 6 votes vote down vote up
static void setCoprocessorError(RpcController controller, Throwable error) {
  if (controller == null) {
    return;
  }
  if (controller instanceof ServerRpcController) {
    if (error instanceof IOException) {
      ((ServerRpcController) controller).setFailedOn((IOException) error);
    } else {
      ((ServerRpcController) controller).setFailedOn(new IOException(error));
    }
  } else if (controller instanceof ClientCoprocessorRpcController) {
    ((ClientCoprocessorRpcController) controller).setFailed(error);
  } else {
    controller.setFailed(error.toString());
  }
}
 
Example 7
Source Project: hbase   Source File: RefreshHFilesClient.java    License: Apache License 2.0 6 votes vote down vote up
public void refreshHFiles(final Table table) throws Throwable {
  final RefreshHFilesProtos.RefreshHFilesRequest request =
          RefreshHFilesProtos.RefreshHFilesRequest.getDefaultInstance();
  table.coprocessorService(RefreshHFilesProtos.RefreshHFilesService.class,
          HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
          new Batch.Call<RefreshHFilesProtos.RefreshHFilesService,
                  RefreshHFilesProtos.RefreshHFilesResponse>() {
      @Override
      public RefreshHFilesProtos.RefreshHFilesResponse call(
            RefreshHFilesProtos.RefreshHFilesService refreshHFilesService)
            throws IOException {
        ServerRpcController controller = new ServerRpcController();
        BlockingRpcCallback<RefreshHFilesProtos.RefreshHFilesResponse> rpcCallback =
              new BlockingRpcCallback<>();
        refreshHFilesService.refreshHFiles(controller, request, rpcCallback);

        if (controller.failedOnException()) {
          throw controller.getFailedOn();
        }

        return rpcCallback.get();
      }
    });
  LOG.debug("Done refreshing HFiles");
}
 
Example 8
Source Project: Kylin   Source File: EndpointTupleIterator.java    License: Apache License 2.0 6 votes vote down vote up
private Iterator<List<IIProtos.IIResponse.IIRow>> getResults(final IIProtos.IIRequest request, HTableInterface table) throws Throwable {
    Map<byte[], List<IIProtos.IIResponse.IIRow>> results = table.coprocessorService(IIProtos.RowsService.class, null, null, new Batch.Call<IIProtos.RowsService, List<IIProtos.IIResponse.IIRow>>() {
        public List<IIProtos.IIResponse.IIRow> call(IIProtos.RowsService rowsService) throws IOException {
            ServerRpcController controller = new ServerRpcController();
            BlockingRpcCallback<IIProtos.IIResponse> rpcCallback = new BlockingRpcCallback<>();
            rowsService.getRows(controller, request, rpcCallback);
            IIProtos.IIResponse response = rpcCallback.get();
            if (controller.failedOnException()) {
                throw controller.getFailedOn();
            }

            return response.getRowsList();
        }
    });

    return results.values().iterator();
}
 
Example 9
Source Project: phoenix   Source File: TestUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void clearMetaDataCache(Connection conn) throws Throwable {
    PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
    Table htable = pconn.getQueryServices().getTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES);
    htable.coprocessorService(MetaDataService.class, HConstants.EMPTY_START_ROW,
        HConstants.EMPTY_END_ROW, new Batch.Call<MetaDataService, ClearCacheResponse>() {
            @Override
            public ClearCacheResponse call(MetaDataService instance) throws IOException {
                ServerRpcController controller = new ServerRpcController();
                BlockingRpcCallback<ClearCacheResponse> rpcCallback =
                        new BlockingRpcCallback<ClearCacheResponse>();
                ClearCacheRequest.Builder builder = ClearCacheRequest.newBuilder();
                instance.clearCache(controller, builder.build(), rpcCallback);
                if(controller.getFailedOn() != null) {
                    throw controller.getFailedOn();
                }
                return rpcCallback.get(); 
            }
          });
}
 
Example 10
@Override
public Collection<TxnMessage.ActiveTxnResponse> getActiveTxns(final TxnMessage.ActiveTxnRequest request) throws IOException{
        Map<byte[], TxnMessage.ActiveTxnResponse> data=coprocessorService(TxnMessage.TxnLifecycleService.class,
                HConstants.EMPTY_START_ROW,HConstants.EMPTY_END_ROW,new Batch.Call<TxnMessage.TxnLifecycleService, TxnMessage.ActiveTxnResponse>(){
                    @Override
                    public TxnMessage.ActiveTxnResponse call(TxnMessage.TxnLifecycleService instance) throws IOException{
                        ServerRpcController controller=new ServerRpcController();
                        BlockingRpcCallback<TxnMessage.ActiveTxnResponse> response=new BlockingRpcCallback<>();

                        instance.getActiveTransactions(controller,request,response);
                        dealWithError(controller);
                        return response.get();
                    }
                });
    return data.values();
}
 
Example 11
@Override
public void bulkWrite(RpcController controller,
                      SpliceMessage.BulkWriteRequest request,
                      RpcCallback<SpliceMessage.BulkWriteResponse> done){
    try{
        byte[] bytes=bulkWrites(request.getBytes().toByteArray());
        if(bytes==null||bytes.length<=0)
            LOG.error("No bytes constructed for the result!");

        SpliceMessage.BulkWriteResponse response =SpliceMessage.BulkWriteResponse.newBuilder()
                .setBytes(ZeroCopyLiteralByteString.wrap(bytes)).build();
        done.run(response);
    }catch(IOException e){
        LOG.error("Unexpected exception performing bulk write: ",e);
        ((ServerRpcController)controller).setFailedOn(e);
    }
}
 
Example 12
Source Project: phoenix   Source File: ConnectionQueryServicesImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MetaDataMutationResult getTable(final PName tenantId, final byte[] schemaBytes, final byte[] tableBytes,
        final long tableTimestamp, final long clientTimestamp) throws SQLException {
    final byte[] tenantIdBytes = tenantId == null ? ByteUtil.EMPTY_BYTE_ARRAY : tenantId.getBytes();
    byte[] tableKey = SchemaUtil.getTableKey(tenantIdBytes, schemaBytes, tableBytes);
    return metaDataCoprocessorExec(tableKey,
        new Batch.Call<MetaDataService, MetaDataResponse>() {
            @Override
            public MetaDataResponse call(MetaDataService instance) throws IOException {
                ServerRpcController controller = new ServerRpcController();
                BlockingRpcCallback<MetaDataResponse> rpcCallback =
                        new BlockingRpcCallback<MetaDataResponse>();
                GetTableRequest.Builder builder = GetTableRequest.newBuilder();
                builder.setTenantId(HBaseZeroCopyByteString.wrap(tenantIdBytes));
                builder.setSchemaName(HBaseZeroCopyByteString.wrap(schemaBytes));
                builder.setTableName(HBaseZeroCopyByteString.wrap(tableBytes));
                builder.setTableTimestamp(tableTimestamp);
                builder.setClientTimestamp(clientTimestamp);

               instance.getTable(controller, builder.build(), rpcCallback);
               if(controller.getFailedOn() != null) {
                   throw controller.getFailedOn();
               }
               return rpcCallback.get();
            }
        });
}
 
Example 13
Source Project: phoenix   Source File: ProtobufUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Stores an exception encountered during RPC invocation so it can be passed back through to the
 * client.
 * @param controller the controller instance provided by the client when calling the service
 * @param ioe the exception encountered
 */
public static void setControllerException(RpcController controller, IOException ioe) {
    if (controller != null) {
        if (controller instanceof ServerRpcController) {
            ((ServerRpcController) controller).setFailedOn(ioe);
        } else {
            controller.setFailed(StringUtils.stringifyException(ioe));
        }
    }
}
 
Example 14
Source Project: yuzhouwan   Source File: QueryExample.java    License: Apache License 2.0 5 votes vote down vote up
public static List<DataProtos.DataQueryResponse.Row> queryByStartRowAndStopRow(String tableName, String startRow, String stopRow, boolean isIncludeEnd, boolean isSalting) {

        final DataProtos.DataQueryRequest.Builder requestBuilder = DataProtos.DataQueryRequest.newBuilder();
        requestBuilder.setTableName(tableName);
        requestBuilder.setStartRow(startRow);
        requestBuilder.setEndRow(stopRow);
        requestBuilder.setIncluedEnd(isIncludeEnd);
        requestBuilder.setIsSalting(isSalting);
        try {
            HTable table = new HTable(HBaseConfiguration.create(conf), tableName);
            Map<byte[], List<DataProtos.DataQueryResponse.Row>> result = table.coprocessorService(DataProtos.QueryDataService.class, null, null, new Batch.Call<DataProtos.QueryDataService, List<DataProtos.DataQueryResponse.Row>>() {
                public List<DataProtos.DataQueryResponse.Row> call(DataProtos.QueryDataService counter) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<DataProtos.DataQueryResponse> rpcCallback = new BlockingRpcCallback<>();
                    counter.queryByStartRowAndEndRow(controller, requestBuilder.build(), rpcCallback);
                    DataProtos.DataQueryResponse response = rpcCallback.get();
                    if (controller.failedOnException()) {
                        throw controller.getFailedOn();
                    }
                    return response.getRowListList();
                }
            });
            List<DataProtos.DataQueryResponse.Row> results = new LinkedList<>();
            result.entrySet()
                    .stream()
                    .filter(entry -> null != entry.getValue())
                    .forEach(entry -> results.addAll(entry.getValue()));
            return results;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
 
Example 15
Source Project: hbase   Source File: Export.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<byte[], Response> run(final Configuration conf, TableName tableName,
    Scan scan, Path dir) throws Throwable {
  FileSystem fs = dir.getFileSystem(conf);
  UserProvider userProvider = UserProvider.instantiate(conf);
  checkDir(fs, dir);
  FsDelegationToken fsDelegationToken = new FsDelegationToken(userProvider, "renewer");
  fsDelegationToken.acquireDelegationToken(fs);
  try {
    final ExportProtos.ExportRequest request = getConfiguredRequest(conf, dir,
      scan, fsDelegationToken.getUserToken());
    try (Connection con = ConnectionFactory.createConnection(conf);
            Table table = con.getTable(tableName)) {
      Map<byte[], Response> result = new TreeMap<>(Bytes.BYTES_COMPARATOR);
      table.coprocessorService(ExportProtos.ExportService.class,
        scan.getStartRow(),
        scan.getStopRow(),
        (ExportProtos.ExportService service) -> {
          ServerRpcController controller = new ServerRpcController();
          Map<byte[], ExportProtos.ExportResponse> rval = new TreeMap<>(Bytes.BYTES_COMPARATOR);
          CoprocessorRpcUtils.BlockingRpcCallback<ExportProtos.ExportResponse>
            rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>();
          service.export(controller, request, rpcCallback);
          if (controller.failedOnException()) {
            throw controller.getFailedOn();
          }
          return rpcCallback.get();
        }).forEach((k, v) -> result.put(k, new Response(v)));
      return result;
    } catch (Throwable e) {
      fs.delete(dir, true);
      throw e;
    }
  } finally {
    fsDelegationToken.releaseDelegationToken();
  }
}
 
Example 16
Source Project: hbase   Source File: TestRegionServerCoprocessorEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEndpointExceptions() throws Exception {
  final ServerName serverName = TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName();
  final ServerRpcController controller = new ServerRpcController();
  final CoprocessorRpcUtils.BlockingRpcCallback<DummyRegionServerEndpointProtos.DummyResponse>
      rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>();
  DummyRegionServerEndpointProtos.DummyService service =
      ProtobufUtil.newServiceStub(DummyRegionServerEndpointProtos.DummyService.class,
          TEST_UTIL.getAdmin().coprocessorService(serverName));
  service.dummyThrow(controller,
      DummyRegionServerEndpointProtos.DummyRequest.getDefaultInstance(), rpcCallback);
  assertEquals(null, rpcCallback.get());
  assertTrue(controller.failedOnException());
  assertEquals(WHAT_TO_THROW.getClass(), controller.getFailedOn().getCause().getClass());
}
 
Example 17
Source Project: hbase   Source File: MasterRpcServices.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientProtos.CoprocessorServiceResponse execMasterService(final RpcController controller,
    final ClientProtos.CoprocessorServiceRequest request) throws ServiceException {
  rpcPreCheck("execMasterService");
  try {
    ServerRpcController execController = new ServerRpcController();
    ClientProtos.CoprocessorServiceCall call = request.getCall();
    String serviceName = call.getServiceName();
    String methodName = call.getMethodName();
    if (!master.coprocessorServiceHandlers.containsKey(serviceName)) {
      throw new UnknownProtocolException(null,
        "No registered Master Coprocessor Endpoint found for " + serviceName +
        ". Has it been enabled?");
    }

    Service service = master.coprocessorServiceHandlers.get(serviceName);
    ServiceDescriptor serviceDesc = service.getDescriptorForType();
    MethodDescriptor methodDesc =
        CoprocessorRpcUtils.getMethodDescriptor(methodName, serviceDesc);

    Message execRequest =
        CoprocessorRpcUtils.getRequest(service, methodDesc, call.getRequest());
    final Message.Builder responseBuilder =
        service.getResponsePrototype(methodDesc).newBuilderForType();
    service.callMethod(methodDesc, execController, execRequest,
      (message) -> {
        if (message != null) {
          responseBuilder.mergeFrom(message);
        }
      });
    Message execResult = responseBuilder.build();
    if (execController.getFailedOn() != null) {
      throw execController.getFailedOn();
    }
    return CoprocessorRpcUtils.getResponse(execResult, HConstants.EMPTY_BYTE_ARRAY);
  } catch (IOException ie) {
    throw new ServiceException(ie);
  }
}
 
Example 18
Source Project: hbase   Source File: VisibilityClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param connection the Connection instance to use.
 * @param user
 * @return labels, the given user is globally authorized for.
 * @throws Throwable
 */
public static GetAuthsResponse getAuths(Connection connection, final String user)
    throws Throwable {
  try (Table table = connection.getTable(LABELS_TABLE_NAME)) {
    Batch.Call<VisibilityLabelsService, GetAuthsResponse> callable =
        new Batch.Call<VisibilityLabelsService, GetAuthsResponse>() {
      ServerRpcController controller = new ServerRpcController();
      CoprocessorRpcUtils.BlockingRpcCallback<GetAuthsResponse> rpcCallback =
          new CoprocessorRpcUtils.BlockingRpcCallback<>();

      @Override
      public GetAuthsResponse call(VisibilityLabelsService service) throws IOException {
        GetAuthsRequest.Builder getAuthReqBuilder = GetAuthsRequest.newBuilder();
        getAuthReqBuilder.setUser(UnsafeByteOperations.unsafeWrap(Bytes.toBytes(user)));
        service.getAuths(controller, getAuthReqBuilder.build(), rpcCallback);
        GetAuthsResponse response = rpcCallback.get();
        if (controller.failedOnException()) {
          throw controller.getFailedOn();
        }
        return response;
      }
    };
    Map<byte[], GetAuthsResponse> result =
        table.coprocessorService(VisibilityLabelsService.class, HConstants.EMPTY_BYTE_ARRAY,
            HConstants.EMPTY_BYTE_ARRAY, callable);
    return result.values().iterator().next(); // There will be exactly one region for labels
    // table and so one entry in result Map.
  }
}
 
Example 19
Source Project: hbase   Source File: VisibilityClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the list of visibility labels defined in the system.
 * @param connection The Connection instance to use.
 * @param regex  The regular expression to filter which labels are returned.
 * @return labels The list of visibility labels defined in the system.
 * @throws Throwable
 */
public static ListLabelsResponse listLabels(Connection connection, final String regex)
    throws Throwable {
  try (Table table = connection.getTable(LABELS_TABLE_NAME)) {
    Batch.Call<VisibilityLabelsService, ListLabelsResponse> callable =
        new Batch.Call<VisibilityLabelsService, ListLabelsResponse>() {
      ServerRpcController controller = new ServerRpcController();
      CoprocessorRpcUtils.BlockingRpcCallback<ListLabelsResponse> rpcCallback =
          new CoprocessorRpcUtils.BlockingRpcCallback<>();

      @Override
      public ListLabelsResponse call(VisibilityLabelsService service) throws IOException {
        ListLabelsRequest.Builder listAuthLabelsReqBuilder = ListLabelsRequest.newBuilder();
        if (regex != null) {
          // Compile the regex here to catch any regex exception earlier.
          Pattern pattern = Pattern.compile(regex);
          listAuthLabelsReqBuilder.setRegex(pattern.toString());
        }
        service.listLabels(controller, listAuthLabelsReqBuilder.build(), rpcCallback);
        ListLabelsResponse response = rpcCallback.get();
        if (controller.failedOnException()) {
          throw controller.getFailedOn();
        }
        return response;
      }
    };
    Map<byte[], ListLabelsResponse> result =
        table.coprocessorService(VisibilityLabelsService.class, HConstants.EMPTY_BYTE_ARRAY,
            HConstants.EMPTY_BYTE_ARRAY, callable);
    return result.values().iterator().next(); // There will be exactly one region for labels
    // table and so one entry in result Map.
  }
}
 
Example 20
Source Project: hbase   Source File: VisibilityClient.java    License: Apache License 2.0 5 votes vote down vote up
private static VisibilityLabelsResponse setOrClearAuths(Connection connection,
    final String[] auths, final String user, final boolean setOrClear)
    throws IOException, ServiceException, Throwable {

  try (Table table = connection.getTable(LABELS_TABLE_NAME)) {
    Batch.Call<VisibilityLabelsService, VisibilityLabelsResponse> callable =
        new Batch.Call<VisibilityLabelsService, VisibilityLabelsResponse>() {
      ServerRpcController controller = new ServerRpcController();
      CoprocessorRpcUtils.BlockingRpcCallback<VisibilityLabelsResponse> rpcCallback =
          new CoprocessorRpcUtils.BlockingRpcCallback<>();

      @Override
      public VisibilityLabelsResponse call(VisibilityLabelsService service) throws IOException {
        SetAuthsRequest.Builder setAuthReqBuilder = SetAuthsRequest.newBuilder();
        setAuthReqBuilder.setUser(UnsafeByteOperations.unsafeWrap(Bytes.toBytes(user)));
        for (String auth : auths) {
          if (auth.length() > 0) {
            setAuthReqBuilder.addAuth((ByteString.copyFromUtf8(auth)));
          }
        }
        if (setOrClear) {
          service.setAuths(controller, setAuthReqBuilder.build(), rpcCallback);
        } else {
          service.clearAuths(controller, setAuthReqBuilder.build(), rpcCallback);
        }
        VisibilityLabelsResponse response = rpcCallback.get();
        if (controller.failedOnException()) {
          throw controller.getFailedOn();
        }
        return response;
      }
    };
    Map<byte[], VisibilityLabelsResponse> result = table.coprocessorService(
        VisibilityLabelsService.class, HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY,
        callable);
    return result.values().iterator().next(); // There will be exactly one region for labels
    // table and so one entry in result Map.
  }
}
 
Example 21
Source Project: hbase   Source File: ResponseConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Stores an exception encountered during RPC invocation so it can be passed back
 * through to the client.
 * @param controller the controller instance provided by the client when calling the service
 * @param ioe the exception encountered
 */
public static void setControllerException(RpcController controller,
    IOException ioe) {
  if (controller != null) {
    if (controller instanceof ServerRpcController) {
      ((ServerRpcController)controller).setFailedOn(ioe);
    } else {
      controller.setFailed(StringUtils.stringifyException(ioe));
    }
  }
}
 
Example 22
Source Project: hbase   Source File: ResponseConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retreivies exception stored during RPC invocation.
 * @param controller the controller instance provided by the client when calling the service
 * @return exception if any, or null; Will return DoNotRetryIOException for string represented
 * failure causes in controller.
 */
@Nullable
public static IOException getControllerException(RpcController controller) throws IOException {
  if (controller != null && controller.failed()) {
    if (controller instanceof ServerRpcController) {
      return ((ServerRpcController)controller).getFailedOn();
    } else {
      return new DoNotRetryIOException(controller.errorText());
    }
  }
  return null;
}
 
Example 23
Source Project: phoenix   Source File: ProtobufUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Stores an exception encountered during RPC invocation so it can be passed back through to the
 * client.
 * @param controller the controller instance provided by the client when calling the service
 * @param ioe the exception encountered
 */
public static void setControllerException(RpcController controller, IOException ioe) {
    if (controller != null) {
        if (controller instanceof ServerRpcController) {
            ((ServerRpcController) controller).setFailedOn(ioe);
        } else {
            controller.setFailed(StringUtils.stringifyException(ioe));
        }
    }
}
 
Example 24
Source Project: phoenix   Source File: IndexUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static MetaDataMutationResult updateIndexState(byte[] indexTableKey, long minTimeStamp,
        Table metaTable, PIndexState newState) throws Throwable {
    // Mimic the Put that gets generated by the client on an update of the index state
    Put put = new Put(indexTableKey);
    put.addColumn(PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES, PhoenixDatabaseMetaData.INDEX_STATE_BYTES,
            newState.getSerializedBytes());
    put.addColumn(PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES, PhoenixDatabaseMetaData.INDEX_DISABLE_TIMESTAMP_BYTES,
            PLong.INSTANCE.toBytes(minTimeStamp));
    put.addColumn(PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES, PhoenixDatabaseMetaData.ASYNC_REBUILD_TIMESTAMP_BYTES,
            PLong.INSTANCE.toBytes(0));
    final List<Mutation> tableMetadata = Collections.<Mutation> singletonList(put);

    final Map<byte[], MetaDataResponse> results = metaTable.coprocessorService(MetaDataService.class, indexTableKey,
            indexTableKey, new Batch.Call<MetaDataService, MetaDataResponse>() {
                @Override
                public MetaDataResponse call(MetaDataService instance) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<MetaDataResponse> rpcCallback = new BlockingRpcCallback<MetaDataResponse>();
                    UpdateIndexStateRequest.Builder builder = UpdateIndexStateRequest.newBuilder();
                    for (Mutation m : tableMetadata) {
                        MutationProto mp = ProtobufUtil.toProto(m);
                        builder.addTableMetadataMutations(mp.toByteString());
                    }
                    builder.setClientVersion(VersionUtil.encodeVersion(PHOENIX_MAJOR_VERSION, PHOENIX_MINOR_VERSION, PHOENIX_PATCH_NUMBER));
                    instance.updateIndexState(controller, builder.build(), rpcCallback);
                    if (controller.getFailedOn() != null) { throw controller.getFailedOn(); }
                    return rpcCallback.get();
                }
            });
    if (results.isEmpty()) { throw new IOException("Didn't get expected result size"); }
    MetaDataResponse tmpResponse = results.values().iterator().next();
    return MetaDataMutationResult.constructFromProto(tmpResponse);
}
 
Example 25
@SuppressWarnings("unchecked")
private Set<String> getCompactedFilesPathsFromHBaseRegionServer() {
    try {
        String regionName = hri.getRegionNameAsString();
        try (Partition partition = SIDriver.driver().getTableFactory().getTable(htd.getTableName())) {
            Map<byte[], List<String>> results = ((SkeletonHBaseClientPartition) partition).coprocessorExec(
                    SpliceMessage.SpliceDerbyCoprocessorService.class,
                    hri.getStartKey(),
                    hri.getStartKey(),
                    instance -> {
                        ServerRpcController controller = new ServerRpcController();
                        SpliceMessage.GetCompactedHFilesRequest message = SpliceMessage.GetCompactedHFilesRequest
                                .newBuilder()
                                .setRegionEncodedName(regionName)
                                .build();

                        CoprocessorRpcUtils.BlockingRpcCallback<SpliceMessage.GetCompactedHFilesResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>();
                        instance.getCompactedHFiles(controller, message, rpcCallback);
                        if (controller.failed()) {
                            Throwable t = Throwables.getRootCause(controller.getFailedOn());
                            if (t instanceof IOException) throw (IOException) t;
                            else throw new IOException(t);
                        }
                        SpliceMessage.GetCompactedHFilesResponse response = rpcCallback.get();
                        return response.getFilePathList();
                    });
            //assert results.size() == 1: results;
            return Sets.newHashSet(results.get(hri.getRegionName()));
        }
    } catch (Throwable e) {
        SpliceLogUtils.error(LOG, "Unable to set Compacted Files from HBase region server", e);
        throw new RuntimeException(e);
    }
}
 
Example 26
public static void setControllerException(RpcController controller, IOException ioe) {
    if (controller != null) {
        if (controller instanceof ServerRpcController) {
            ((ServerRpcController)controller).setFailedOn(ioe);
        } else {
            controller.setFailed(StringUtils.stringifyException(ioe));
        }
    }
}
 
Example 27
@Override
public void beginTransaction(byte[] rowKey,TxnMessage.TxnInfo txnInfo) throws IOException{
    TxnMessage.TxnLifecycleService service=getLifecycleService(rowKey);
    ServerRpcController controller=new ServerRpcController();
    service.beginTransaction(controller,txnInfo,new BlockingRpcCallback<>());
    dealWithError(controller);
}
 
Example 28
@Override
public TxnMessage.ActionResponse lifecycleAction(byte[] rowKey,TxnMessage.TxnLifecycleMessage lifecycleMessage) throws IOException{
    TxnMessage.TxnLifecycleService service=getLifecycleService(rowKey);
    ServerRpcController controller=new ServerRpcController();
    BlockingRpcCallback<TxnMessage.ActionResponse> done=new BlockingRpcCallback<>();
    service.lifecycleAction(controller,lifecycleMessage,done);
    dealWithError(controller);
    return done.get();
}
 
Example 29
@Override
public void elevate(byte[] rowKey,TxnMessage.ElevateRequest elevateRequest) throws IOException{
    TxnMessage.TxnLifecycleService service=getLifecycleService(rowKey);

    ServerRpcController controller=new ServerRpcController();
    service.elevateTransaction(controller,elevateRequest,new BlockingRpcCallback<TxnMessage.VoidResponse>());
    dealWithError(controller);
}
 
Example 30
@Override
public TxnMessage.TaskId getTaskId(byte[] rowKey,TxnMessage.TxnRequest request) throws IOException{
    TxnMessage.TxnLifecycleService service=getLifecycleService(rowKey);
    ServerRpcController controller=new ServerRpcController();
    BlockingRpcCallback<TxnMessage.TaskId> done=new BlockingRpcCallback<>();
    service.getTaskId(controller,request,done);
    dealWithError(controller);
    return done.get();
}