下面列出了怎么用org.apache.hadoop.hbase.TableExistsException的API类实例代码及写法,或者点击链接到github查看源代码。
public static void create() throws Exception {
HBaseAdmin admin = new HBaseAdmin(cfg);
if (admin.tableExists(tableName)) {
System.out.println("[info]table has created!");
} else {
try {
TableName table = TableName.valueOf(tableName);
HTableDescriptor tableDescriptor = new HTableDescriptor(table);
tableDescriptor.addFamily(new HColumnDescriptor(familyName));
admin.createTable(tableDescriptor);
} catch (TableExistsException e) {
System.out.println("[warning] table exists!");
}
}
System.out.println("[info]create table success!");
}
public static void create() throws Exception
{
HBaseAdmin admin = new HBaseAdmin(cfg);
if (admin.tableExists(tableName)) {
System.out.println("[info]table has created!");
} else {
TableName table = TableName.valueOf(tableName);
HTableDescriptor tableDescriptor = new HTableDescriptor(table);
tableDescriptor.addFamily(new HColumnDescriptor(familyName));
try{
admin.createTable(tableDescriptor);
}catch(TableExistsException e)
{
System.out.println("[warning] table exists!");
}
}
System.out.println("[info]create table success!");
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}", stateTable.getNameWithNamespaceInclAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try {
if (hBaseAdmin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {}:{} since it already exists.",
stateTable.getNamespaceAsString(), stateTable.getNameAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
hBaseAdmin.createTable(htd);
LOG.info("Created pruneTable {}:{}", stateTable.getNamespaceAsString(), stateTable.getNameAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {}:{} since it already exists.",
stateTable.getNamespaceAsString(), stateTable.getNameAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}", stateTable.getNameWithNamespaceInclAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}", stateTable.getNameWithNamespaceInclAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}", stateTable.getNameWithNamespaceInclAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {}:{} since it already exists.",
stateTable.getNamespaceAsString(), stateTable.getNameAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}:{}", stateTable.getNamespaceAsString(), stateTable.getNameAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {}:{} since it already exists.",
stateTable.getNamespaceAsString(), stateTable.getNameAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}", stateTable.getNameWithNamespaceInclAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString(), ex);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try {
if (hBaseAdmin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {}:{} since it already exists.",
stateTable.getNamespaceAsString(), stateTable.getNameAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
hBaseAdmin.createTable(htd);
LOG.info("Created pruneTable {}:{}", stateTable.getNamespaceAsString(), stateTable.getNameAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {}:{} since it already exists.",
stateTable.getNamespaceAsString(), stateTable.getNameAsString(), ex);
}
}
@Override
protected void rollbackState(final MasterProcedureEnv env, final CreateTableState state)
throws IOException {
if (state == CreateTableState.CREATE_TABLE_PRE_OPERATION) {
// nothing to rollback, pre-create is just table-state checks.
// We can fail if the table does exist or the descriptor is malformed.
// TODO: coprocessor rollback semantic is still undefined.
if (hasException() /* avoid NPE */ &&
getException().getCause().getClass() != TableExistsException.class) {
DeleteTableProcedure.deleteTableStates(env, getTableName());
final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
if (cpHost != null) {
cpHost.postDeleteTable(getTableName());
}
}
releaseSyncLatch();
return;
}
// The procedure doesn't have a rollback. The execution will succeed, at some point.
throw new UnsupportedOperationException("unhandled state=" + state);
}
@Test(expected=TableExistsException.class)
public void testCreateExisting() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
final TableDescriptor htd = MasterProcedureTestingUtility.createHTD(tableName, "f");
final RegionInfo[] regions = ModifyRegionUtils.createRegionInfos(htd, null);
// create the table
long procId1 = procExec.submitProcedure(
new CreateTableProcedure(procExec.getEnvironment(), htd, regions));
// create another with the same name
ProcedurePrepareLatch latch2 = new ProcedurePrepareLatch.CompatibilityLatch();
long procId2 = procExec.submitProcedure(
new CreateTableProcedure(procExec.getEnvironment(), htd, regions, latch2));
ProcedureTestingUtility.waitProcedure(procExec, procId1);
ProcedureTestingUtility.assertProcNotFailed(procExec.getResult(procId1));
ProcedureTestingUtility.waitProcedure(procExec, procId2);
latch2.await();
}
@Test
public void testCloneSnapshotToSameTable() throws Exception {
// take the snapshot
SnapshotProtos.SnapshotDescription snapshotDesc = getSnapshot();
final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
final TableName clonedTableName = TableName.valueOf(snapshotDesc.getTable());
final TableDescriptor htd = createTableDescriptor(clonedTableName, CF);
long procId = ProcedureTestingUtility.submitAndWait(
procExec, new CloneSnapshotProcedure(procExec.getEnvironment(), htd, snapshotDesc));
Procedure<?> result = procExec.getResult(procId);
assertTrue(result.isFailed());
LOG.debug("Clone snapshot failed with exception: " + result.getException());
assertTrue(
ProcedureTestingUtility.getExceptionCause(result) instanceof TableExistsException);
}
/**
* Creates a table with given table name and specified number of column
* families if the table does not already exist.
*/
public void setupTable(TableName table, int cfs) throws IOException {
try {
LOG.info("Creating table " + table);
TableDescriptorBuilder tableDescriptorBuilder =
TableDescriptorBuilder.newBuilder(table);
tableDescriptorBuilder.setCoprocessor(MyObserver.class.getName());
MyObserver.sleepDuration = this.sleepDuration;
for (int i = 0; i < 10; i++) {
ColumnFamilyDescriptor columnFamilyDescriptor =
ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(family(i))).build();
tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
}
UTIL.getAdmin().createTable(tableDescriptorBuilder.build());
} catch (TableExistsException tee) {
LOG.info("Table " + table + " already exists");
}
}
private static void create(Admin admin, TableName tableName, byte[]... families)
throws IOException {
TableDescriptorBuilder.ModifyableTableDescriptor tableDescriptor =
new TableDescriptorBuilder.ModifyableTableDescriptor(tableName);
for (byte[] family : families) {
ColumnFamilyDescriptorBuilder.ModifyableColumnFamilyDescriptor familyDescriptor =
new ColumnFamilyDescriptorBuilder.ModifyableColumnFamilyDescriptor(family);
familyDescriptor.setMaxVersions(1);
familyDescriptor.setCompressionType(Algorithm.GZ);
tableDescriptor.setColumnFamily(familyDescriptor);
}
try {
admin.createTable(tableDescriptor);
} catch (TableExistsException tee) {
/* Ignore */
}
}
@Override
public CompletableFuture<Void> cloneSnapshot(String snapshotName, TableName tableName,
boolean restoreAcl) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exists, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else if (exists) {
future.completeExceptionally(new TableExistsException(tableName));
} else {
completeConditionalOnFuture(future,
internalRestoreSnapshot(snapshotName, tableName, restoreAcl));
}
});
return future;
}
@Override
public void completionCleanup(final Procedure proc) {
if (proc instanceof TableProcedureInterface) {
TableProcedureInterface iProcTable = (TableProcedureInterface) proc;
boolean tableDeleted;
if (proc.hasException()) {
Exception procEx = proc.getException().unwrapRemoteException();
if (iProcTable.getTableOperationType() == TableOperationType.CREATE) {
// create failed because the table already exist
tableDeleted = !(procEx instanceof TableExistsException);
} else {
// the operation failed because the table does not exist
tableDeleted = (procEx instanceof TableNotFoundException);
}
} else {
// the table was deleted
tableDeleted = (iProcTable.getTableOperationType() == TableOperationType.DELETE);
}
if (tableDeleted) {
markTableAsDeleted(iProcTable.getTableName(), proc);
return;
}
} else if (proc instanceof PeerProcedureInterface) {
tryCleanupPeerQueue(getPeerId(proc), proc);
} else if (proc instanceof ServerProcedureInterface) {
tryCleanupServerQueue(getServerName(proc), proc);
} else {
// No cleanup for other procedure types, yet.
return;
}
}
private boolean prepareCreate(final MasterProcedureEnv env) throws IOException {
final TableName tableName = getTableName();
if (MetaTableAccessor.tableExists(env.getMasterServices().getConnection(), tableName)) {
setFailure("master-create-table", new TableExistsException(getTableName()));
return false;
}
// check that we have at least 1 CF
if (tableDescriptor.getColumnFamilyCount() == 0) {
setFailure("master-create-table", new DoNotRetryIOException(
"Table " + getTableName().toString() + " should have at least one column family."));
return false;
}
if (!tableName.isSystemTable()) {
// do not check rs group for system tables as we may block the bootstrap.
Supplier<String> forWhom = () -> "table " + tableName;
RSGroupInfo rsGroupInfo = MasterProcedureUtil.checkGroupExists(
env.getMasterServices().getRSGroupInfoManager()::getRSGroup,
tableDescriptor.getRegionServerGroup(), forWhom);
if (rsGroupInfo == null) {
// we do not set rs group info on table, check if we have one on namespace
String namespace = tableName.getNamespaceAsString();
NamespaceDescriptor nd = env.getMasterServices().getClusterSchema().getNamespace(namespace);
forWhom = () -> "table " + tableName + "(inherit from namespace)";
rsGroupInfo = MasterProcedureUtil.checkGroupExists(
env.getMasterServices().getRSGroupInfoManager()::getRSGroup,
MasterProcedureUtil.getNamespaceGroup(nd), forWhom);
}
MasterProcedureUtil.checkGroupNotEmpty(rsGroupInfo, forWhom);
}
return true;
}
/**
* Action before any real action of cloning from snapshot.
* @param env MasterProcedureEnv
* @throws IOException
*/
private void prepareClone(final MasterProcedureEnv env) throws IOException {
final TableName tableName = getTableName();
if (MetaTableAccessor.tableExists(env.getMasterServices().getConnection(), tableName)) {
throw new TableExistsException(getTableName());
}
}
/**
* Check quota to create table.
* We add the table information to namespace state cache, assuming the operation will
* pass. If the operation fails, then the next time namespace state chore runs
* namespace state cache will be corrected.
*
* @param tName - The table name to check quota.
* @param regions - Number of regions that will be added.
* @throws IOException Signals that an I/O exception has occurred.
*/
public void checkQuotaToCreateTable(TableName tName, int regions) throws IOException {
if (stateManager.isInitialized()) {
// We do this check to fail fast.
if (MetaTableAccessor.tableExists(this.masterServices.getConnection(), tName)) {
throw new TableExistsException(tName);
}
stateManager.checkAndUpdateNamespaceTableCount(tName, regions);
} else {
checkTableTypeAndThrowException(tName);
}
}
/**
* Creates a table with given table name and specified number of column families if the table does
* not already exist.
*/
private void setupTable(final Connection connection, TableName table, int cfs)
throws IOException {
try {
LOG.info("Creating table " + table);
try (Admin admin = connection.getAdmin()) {
admin.createTable(createTableDesc(table, cfs));
}
} catch (TableExistsException tee) {
LOG.info("Table " + table + " already exists");
}
}
/**
* Creates a table with given table name,specified number of column families<br>
* and splitkeys if the table does not already exist.
* @param table
* @param cfs
* @param SPLIT_KEYS
*/
private void setupTableWithSplitkeys(TableName table, int cfs, byte[][] SPLIT_KEYS)
throws IOException {
try {
LOG.info("Creating table " + table);
util.createTable(createTableDesc(table, cfs), SPLIT_KEYS);
} catch (TableExistsException tee) {
LOG.info("Table " + table + " already exists");
}
}
@Test
public void testCloneTableSchemaWithExistentDestinationTable() throws Exception {
final TableName newTableName = TableName.valueOf(tableName.getNameAsString() + "_new");
byte[] FAMILY_0 = Bytes.toBytes("cf0");
TEST_UTIL.createTable(tableName, FAMILY_0);
TEST_UTIL.createTable(newTableName, FAMILY_0);
// test for existent destination table
try {
admin.cloneTableSchema(tableName, newTableName, false).join();
fail("Should have failed when destination table exists.");
} catch (CompletionException e) {
assertTrue(e.getCause() instanceof TableExistsException);
}
}
@Test
public void testCloneTableSchemaWithExistentDestinationTable() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
final TableName newTableName = TableName.valueOf(tableName.getNameAsString() + "_new");
byte[] FAMILY_0 = Bytes.toBytes("cf0");
TEST_UTIL.createTable(tableName, FAMILY_0);
TEST_UTIL.createTable(newTableName, FAMILY_0);
// test for existent destination table
try {
ADMIN.cloneTableSchema(tableName, newTableName, false);
fail("Should have failed to create a existent table.");
} catch (TableExistsException ex) {
// expected
}
}
/**
* For HADOOP-2579
*/
@Test (expected=TableExistsException.class)
public void testTableExistsExceptionWithATable() throws IOException {
final TableName name = TableName.valueOf(this.name.getMethodName());
TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY).close();
TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
}
@Test
public void testNotMoveTableToNullRSGroupWhenCreatingExistingTable() throws Exception {
// Trigger
TableName tn1 = TableName.valueOf("t1");
TEST_UTIL.createTable(tn1, "cf1");
try {
// Create an existing table to trigger HBASE-21866
TEST_UTIL.createTable(tn1, "cf1");
} catch (TableExistsException teex) {
// Ignore
}
// Wait then verify
// Could not verify until the rollback of CreateTableProcedure is done
// (that is, the coprocessor finishes its work),
// or the table is still in the "default" rsgroup even though HBASE-21866
// is not fixed.
TEST_UTIL.waitFor(5000, new Waiter.Predicate<Exception>() {
@Override
public boolean evaluate() throws Exception {
return MASTER.getMasterProcedureExecutor().getActiveExecutorCount() == 0;
}
});
Set<TableName> tables = Sets.newHashSet(ADMIN.listTablesInRSGroup(RSGroupInfo.DEFAULT_GROUP));
assertTrue("Table 't1' must be in 'default' rsgroup", tables.contains(tn1));
// Cleanup
TEST_UTIL.deleteTable(tn1);
}
@Override
public TableDescriptor get(TableName tablename)
throws TableExistsException, FileNotFoundException, IOException {
LOG.info((super.isUsecache() ? "Cached" : "Non-Cached") +
" TableDescriptor.get() on " + tablename + ", cachehits=" + this.cachehits);
return super.get(tablename);
}
@Override
public Future<Void> cloneSnapshotAsync(String snapshotName, TableName tableName, boolean cloneAcl)
throws IOException, TableExistsException, RestoreSnapshotException {
throw new NotImplementedException("cloneSnapshotAsync not supported in ThriftAdmin");
}
public Future<Void> cloneSnapshotAsync(String snapshotName, TableName tableName,
boolean restoreAcl) throws IOException, TableExistsException, RestoreSnapshotException {
return admin.cloneSnapshotAsync(snapshotName, tableName, restoreAcl);
}
@Test public void testTableDescriptors()
throws IOException, InterruptedException {
final String name = this.name.getMethodName();
FileSystem fs = FileSystem.get(UTIL.getConfiguration());
// Cleanup old tests if any debris laying around.
Path rootdir = new Path(UTIL.getDataTestDir(), name);
FSTableDescriptors htds = new FSTableDescriptors(fs, rootdir) {
@Override
public TableDescriptor get(TableName tablename)
throws TableExistsException, FileNotFoundException, IOException {
LOG.info(tablename + ", cachehits=" + this.cachehits);
return super.get(tablename);
}
};
final int count = 10;
// Write out table infos.
for (int i = 0; i < count; i++) {
htds.createTableDescriptor(TableDescriptorBuilder.newBuilder(TableName.valueOf(name + i)).build());
}
for (int i = 0; i < count; i++) {
assertTrue(htds.get(TableName.valueOf(name + i)) != null);
}
for (int i = 0; i < count; i++) {
assertTrue(htds.get(TableName.valueOf(name + i)) != null);
}
// Update the table infos
for (int i = 0; i < count; i++) {
TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(TableName.valueOf(name + i));
builder.setColumnFamily(ColumnFamilyDescriptorBuilder.of("" + i));
htds.updateTableDescriptor(builder.build());
}
// Wait a while so mod time we write is for sure different.
Thread.sleep(100);
for (int i = 0; i < count; i++) {
assertTrue(htds.get(TableName.valueOf(name + i)) != null);
}
for (int i = 0; i < count; i++) {
assertTrue(htds.get(TableName.valueOf(name + i)) != null);
}
assertEquals(count * 4, htds.invocations);
assertTrue("expected=" + (count * 2) + ", actual=" + htds.cachehits,
htds.cachehits >= (count * 2));
}