View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.client;
20  
21  import java.io.IOException;
22  import java.io.InterruptedIOException;
23  import java.net.SocketTimeoutException;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.HashMap;
27  import java.util.LinkedList;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Map.Entry;
31  import java.util.concurrent.atomic.AtomicInteger;
32  import java.util.concurrent.atomic.AtomicReference;
33  import java.util.concurrent.ExecutionException;
34  import java.util.concurrent.Future;
35  import java.util.concurrent.TimeUnit;
36  import java.util.concurrent.TimeoutException;
37  import java.util.regex.Pattern;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  import org.apache.hadoop.conf.Configuration;
42  import org.apache.hadoop.hbase.Abortable;
43  import org.apache.hadoop.hbase.ClusterStatus;
44  import org.apache.hadoop.hbase.DoNotRetryIOException;
45  import org.apache.hadoop.hbase.HBaseConfiguration;
46  import org.apache.hadoop.hbase.HColumnDescriptor;
47  import org.apache.hadoop.hbase.HConstants;
48  import org.apache.hadoop.hbase.HRegionInfo;
49  import org.apache.hadoop.hbase.HRegionLocation;
50  import org.apache.hadoop.hbase.HTableDescriptor;
51  import org.apache.hadoop.hbase.MasterNotRunningException;
52  import org.apache.hadoop.hbase.MetaTableAccessor;
53  import org.apache.hadoop.hbase.NamespaceDescriptor;
54  import org.apache.hadoop.hbase.NotServingRegionException;
55  import org.apache.hadoop.hbase.RegionException;
56  import org.apache.hadoop.hbase.RegionLocations;
57  import org.apache.hadoop.hbase.ServerName;
58  import org.apache.hadoop.hbase.TableExistsException;
59  import org.apache.hadoop.hbase.TableName;
60  import org.apache.hadoop.hbase.TableNotDisabledException;
61  import org.apache.hadoop.hbase.TableNotEnabledException;
62  import org.apache.hadoop.hbase.TableNotFoundException;
63  import org.apache.hadoop.hbase.UnknownRegionException;
64  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
65  import org.apache.hadoop.hbase.classification.InterfaceAudience;
66  import org.apache.hadoop.hbase.classification.InterfaceStability;
67  import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
68  import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
69  import org.apache.hadoop.hbase.exceptions.DeserializationException;
70  import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
71  import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
72  import org.apache.hadoop.hbase.ipc.MasterCoprocessorRpcChannel;
73  import org.apache.hadoop.hbase.ipc.RegionServerCoprocessorRpcChannel;
74  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
75  import org.apache.hadoop.hbase.protobuf.RequestConverter;
76  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
77  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
78  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
79  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest;
80  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest;
81  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
82  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
83  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
84  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterRequest;
85  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterResponse;
86  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.StopServerRequest;
87  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.UpdateConfigurationRequest;
88  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
89  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
90  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ProcedureDescription;
91  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
92  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
93  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.TableSchema;
94  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AddColumnRequest;
95  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AssignRegionRequest;
96  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateNamespaceRequest;
97  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
98  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableResponse;
99  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteColumnRequest;
100 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteNamespaceRequest;
101 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
102 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableRequest;
103 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableResponse;
104 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableRequest;
105 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableResponse;
106 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DispatchMergingRegionsRequest;
107 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableRequest;
108 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableResponse;
109 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ExecProcedureRequest;
110 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ExecProcedureResponse;
111 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetClusterStatusRequest;
112 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
113 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest;
114 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetProcedureResultRequest;
115 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetProcedureResultResponse;
116 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusRequest;
117 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusResponse;
118 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsRequest;
119 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
120 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableNamesRequest;
121 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsProcedureDoneRequest;
122 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsProcedureDoneResponse;
123 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneRequest;
124 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneResponse;
125 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
126 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
127 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest;
128 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest;
129 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest;
130 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampForRegionRequest;
131 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampRequest;
132 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyColumnRequest;
133 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyNamespaceRequest;
134 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyTableRequest;
135 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MoveRegionRequest;
136 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotRequest;
137 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotResponse;
138 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetBalancerRunningRequest;
139 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ShutdownRequest;
140 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotRequest;
141 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotResponse;
142 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.StopMasterRequest;
143 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.TruncateTableRequest;
144 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.UnassignRegionRequest;
145 import org.apache.hadoop.hbase.quotas.QuotaFilter;
146 import org.apache.hadoop.hbase.quotas.QuotaRetriever;
147 import org.apache.hadoop.hbase.quotas.QuotaSettings;
148 import org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException;
149 import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
150 import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException;
151 import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
152 import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
153 import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
154 import org.apache.hadoop.hbase.util.Addressing;
155 import org.apache.hadoop.hbase.util.Bytes;
156 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
157 import org.apache.hadoop.hbase.util.ForeignExceptionUtil;
158 import org.apache.hadoop.hbase.util.Pair;
159 import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
160 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
161 import org.apache.hadoop.ipc.RemoteException;
162 import org.apache.hadoop.util.StringUtils;
163 import org.apache.zookeeper.KeeperException;
164 
165 import com.google.common.annotations.VisibleForTesting;
166 import com.google.protobuf.ByteString;
167 import com.google.protobuf.ServiceException;
168 
169 /**
170  * HBaseAdmin is no longer a client API. It is marked InterfaceAudience.Private indicating that
171  * this is an HBase-internal class as defined in
172  * https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/InterfaceClassification.html
173  * There are no guarantees for backwards source / binary compatibility and methods or class can
174  * change or go away without deprecation.
175  * Use {@link Connection#getAdmin()} to obtain an instance of {@link Admin} instead of constructing
176  * an HBaseAdmin directly.
177  *
178  * <p>Connection should be an <i>unmanaged</i> connection obtained via
179  * {@link ConnectionFactory#createConnection(Configuration)}
180  *
181  * @see ConnectionFactory
182  * @see Connection
183  * @see Admin
184  */
185 @InterfaceAudience.Private
186 @InterfaceStability.Evolving
187 public class HBaseAdmin implements Admin {
188   private static final Log LOG = LogFactory.getLog(HBaseAdmin.class);
189 
190   private static final String ZK_IDENTIFIER_PREFIX =  "hbase-admin-on-";
191 
192   private ClusterConnection connection;
193 
194   private volatile Configuration conf;
195   private final long pause;
196   private final int numRetries;
197   // Some operations can take a long time such as disable of big table.
198   // numRetries is for 'normal' stuff... Multiply by this factor when
199   // want to wait a long time.
200   private final int retryLongerMultiplier;
201   private final int syncWaitTimeout;
202   private boolean aborted;
203   private boolean cleanupConnectionOnClose = false; // close the connection in close()
204   private boolean closed = false;
205   private int operationTimeout;
206 
207   private RpcRetryingCallerFactory rpcCallerFactory;
208 
209   /**
210    * Constructor.
211    * See {@link #HBaseAdmin(Connection connection)}
212    *
213    * @param c Configuration object. Copied internally.
214    * @deprecated Constructing HBaseAdmin objects manually has been deprecated.
215    * Use {@link Connection#getAdmin()} to obtain an instance of {@link Admin} instead.
216    */
217   @Deprecated
218   public HBaseAdmin(Configuration c)
219   throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
220     // Will not leak connections, as the new implementation of the constructor
221     // does not throw exceptions anymore.
222     this(ConnectionManager.getConnectionInternal(new Configuration(c)));
223     this.cleanupConnectionOnClose = true;
224   }
225 
226   @Override
227   public int getOperationTimeout() {
228     return operationTimeout;
229   }
230 
231 
232   /**
233    * Constructor for externally managed Connections.
234    * The connection to master will be created when required by admin functions.
235    *
236    * @param connection The Connection instance to use
237    * @throws MasterNotRunningException, ZooKeeperConnectionException are not
238    *  thrown anymore but kept into the interface for backward api compatibility
239    * @deprecated Constructing HBaseAdmin objects manually has been deprecated.
240    * Use {@link Connection#getAdmin()} to obtain an instance of {@link Admin} instead.
241    */
242   @Deprecated
243   public HBaseAdmin(Connection connection)
244       throws MasterNotRunningException, ZooKeeperConnectionException {
245     this((ClusterConnection)connection);
246   }
247 
248   HBaseAdmin(ClusterConnection connection) {
249     this.conf = connection.getConfiguration();
250     this.connection = connection;
251 
252     this.pause = this.conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
253         HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
254     this.numRetries = this.conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
255         HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
256     this.retryLongerMultiplier = this.conf.getInt(
257         "hbase.client.retries.longer.multiplier", 10);
258     this.operationTimeout = this.conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
259         HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
260     this.syncWaitTimeout = this.conf.getInt(
261       "hbase.client.sync.wait.timeout.msec", 10 * 60000); // 10min
262 
263     this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(this.conf);
264   }
265 
266   @Override
267   public void abort(String why, Throwable e) {
268     // Currently does nothing but throw the passed message and exception
269     this.aborted = true;
270     throw new RuntimeException(why, e);
271   }
272 
273   @Override
274   public boolean isAborted(){
275     return this.aborted;
276   }
277 
278   /** @return HConnection used by this object. */
279   @Override
280   public HConnection getConnection() {
281     return connection;
282   }
283 
284   /** @return - true if the master server is running. Throws an exception
285    *  otherwise.
286    * @throws ZooKeeperConnectionException
287    * @throws MasterNotRunningException
288    * @deprecated this has been deprecated without a replacement
289    */
290   @Deprecated
291   public boolean isMasterRunning()
292   throws MasterNotRunningException, ZooKeeperConnectionException {
293     return connection.isMasterRunning();
294   }
295 
296   /**
297    * @param tableName Table to check.
298    * @return True if table exists already.
299    * @throws IOException
300    */
301   @Override
302   public boolean tableExists(final TableName tableName) throws IOException {
303     return MetaTableAccessor.tableExists(connection, tableName);
304   }
305 
306   public boolean tableExists(final byte[] tableName)
307   throws IOException {
308     return tableExists(TableName.valueOf(tableName));
309   }
310 
311   public boolean tableExists(final String tableName)
312   throws IOException {
313     return tableExists(TableName.valueOf(tableName));
314   }
315 
316   @Override
317   public HTableDescriptor[] listTables() throws IOException {
318     return listTables((Pattern)null, false);
319   }
320 
321   @Override
322   public HTableDescriptor[] listTables(Pattern pattern) throws IOException {
323     return listTables(pattern, false);
324   }
325 
326   @Override
327   public HTableDescriptor[] listTables(String regex) throws IOException {
328     return listTables(Pattern.compile(regex), false);
329   }
330 
331   @Override
332   public HTableDescriptor[] listTables(final Pattern pattern, final boolean includeSysTables)
333       throws IOException {
334     return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
335       @Override
336       public HTableDescriptor[] call(int callTimeout) throws ServiceException {
337         GetTableDescriptorsRequest req =
338             RequestConverter.buildGetTableDescriptorsRequest(pattern, includeSysTables);
339         return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
340       }
341     });
342   }
343 
344   @Override
345   public HTableDescriptor[] listTables(String regex, boolean includeSysTables)
346       throws IOException {
347     return listTables(Pattern.compile(regex), includeSysTables);
348   }
349 
350   /**
351    * List all of the names of userspace tables.
352    * @return String[] table names
353    * @throws IOException if a remote or network exception occurs
354    * @deprecated Use {@link Admin#listTableNames()} instead
355    */
356   @Deprecated
357   public String[] getTableNames() throws IOException {
358     TableName[] tableNames = listTableNames();
359     String result[] = new String[tableNames.length];
360     for (int i = 0; i < tableNames.length; i++) {
361       result[i] = tableNames[i].getNameAsString();
362     }
363     return result;
364   }
365 
366   /**
367    * List all of the names of userspace tables matching the given regular expression.
368    * @param pattern The regular expression to match against
369    * @return String[] table names
370    * @throws IOException if a remote or network exception occurs
371    * @deprecated Use {@link Admin#listTableNames(Pattern)} instead.
372    */
373   @Deprecated
374   public String[] getTableNames(Pattern pattern) throws IOException {
375     TableName[] tableNames = listTableNames(pattern);
376     String result[] = new String[tableNames.length];
377     for (int i = 0; i < tableNames.length; i++) {
378       result[i] = tableNames[i].getNameAsString();
379     }
380     return result;
381   }
382 
383   /**
384    * List all of the names of userspace tables matching the given regular expression.
385    * @param regex The regular expression to match against
386    * @return String[] table names
387    * @throws IOException if a remote or network exception occurs
388    * @deprecated Use {@link Admin#listTableNames(Pattern)} instead.
389    */
390   @Deprecated
391   public String[] getTableNames(String regex) throws IOException {
392     return getTableNames(Pattern.compile(regex));
393   }
394 
395   @Override
396   public TableName[] listTableNames() throws IOException {
397     return listTableNames((Pattern)null, false);
398   }
399 
400   @Override
401   public TableName[] listTableNames(Pattern pattern) throws IOException {
402     return listTableNames(pattern, false);
403   }
404 
405   @Override
406   public TableName[] listTableNames(String regex) throws IOException {
407     return listTableNames(Pattern.compile(regex), false);
408   }
409 
410   @Override
411   public TableName[] listTableNames(final Pattern pattern, final boolean includeSysTables)
412       throws IOException {
413     return executeCallable(new MasterCallable<TableName[]>(getConnection()) {
414       @Override
415       public TableName[] call(int callTimeout) throws ServiceException {
416         GetTableNamesRequest req =
417             RequestConverter.buildGetTableNamesRequest(pattern, includeSysTables);
418         return ProtobufUtil.getTableNameArray(master.getTableNames(null, req)
419             .getTableNamesList());
420       }
421     });
422   }
423 
424   @Override
425   public TableName[] listTableNames(final String regex, final boolean includeSysTables)
426       throws IOException {
427     return listTableNames(Pattern.compile(regex), includeSysTables);
428   }
429 
430   /**
431    * Method for getting the tableDescriptor
432    * @param tableName as a byte []
433    * @return the tableDescriptor
434    * @throws TableNotFoundException
435    * @throws IOException if a remote or network exception occurs
436    */
437   @Override
438   public HTableDescriptor getTableDescriptor(final TableName tableName)
439   throws TableNotFoundException, IOException {
440     if (tableName == null) return null;
441     HTableDescriptor htd = executeCallable(new MasterCallable<HTableDescriptor>(getConnection()) {
442       @Override
443       public HTableDescriptor call(int callTimeout) throws ServiceException {
444         GetTableDescriptorsResponse htds;
445         GetTableDescriptorsRequest req =
446             RequestConverter.buildGetTableDescriptorsRequest(tableName);
447         htds = master.getTableDescriptors(null, req);
448 
449         if (!htds.getTableSchemaList().isEmpty()) {
450           return HTableDescriptor.convert(htds.getTableSchemaList().get(0));
451         }
452         return null;
453       }
454     });
455     if (htd != null) {
456       return htd;
457     }
458     throw new TableNotFoundException(tableName.getNameAsString());
459   }
460 
461   public HTableDescriptor getTableDescriptor(final byte[] tableName)
462   throws TableNotFoundException, IOException {
463     return getTableDescriptor(TableName.valueOf(tableName));
464   }
465 
466   private long getPauseTime(int tries) {
467     int triesCount = tries;
468     if (triesCount >= HConstants.RETRY_BACKOFF.length) {
469       triesCount = HConstants.RETRY_BACKOFF.length - 1;
470     }
471     return this.pause * HConstants.RETRY_BACKOFF[triesCount];
472   }
473 
474   /**
475    * Creates a new table.
476    * Synchronous operation.
477    *
478    * @param desc table descriptor for table
479    *
480    * @throws IllegalArgumentException if the table name is reserved
481    * @throws MasterNotRunningException if master is not running
482    * @throws TableExistsException if table already exists (If concurrent
483    * threads, the table may have been created between test-for-existence
484    * and attempt-at-creation).
485    * @throws IOException if a remote or network exception occurs
486    */
487   @Override
488   public void createTable(HTableDescriptor desc)
489   throws IOException {
490     createTable(desc, null);
491   }
492 
493   /**
494    * Creates a new table with the specified number of regions.  The start key
495    * specified will become the end key of the first region of the table, and
496    * the end key specified will become the start key of the last region of the
497    * table (the first region has a null start key and the last region has a
498    * null end key).
499    *
500    * BigInteger math will be used to divide the key range specified into
501    * enough segments to make the required number of total regions.
502    *
503    * Synchronous operation.
504    *
505    * @param desc table descriptor for table
506    * @param startKey beginning of key range
507    * @param endKey end of key range
508    * @param numRegions the total number of regions to create
509    *
510    * @throws IllegalArgumentException if the table name is reserved
511    * @throws MasterNotRunningException if master is not running
512    * @throws org.apache.hadoop.hbase.TableExistsException if table already exists (If concurrent
513    * threads, the table may have been created between test-for-existence
514    * and attempt-at-creation).
515    * @throws IOException
516    */
517   @Override
518   public void createTable(HTableDescriptor desc, byte [] startKey,
519       byte [] endKey, int numRegions)
520   throws IOException {
521     if(numRegions < 3) {
522       throw new IllegalArgumentException("Must create at least three regions");
523     } else if(Bytes.compareTo(startKey, endKey) >= 0) {
524       throw new IllegalArgumentException("Start key must be smaller than end key");
525     }
526     if (numRegions == 3) {
527       createTable(desc, new byte[][]{startKey, endKey});
528       return;
529     }
530     byte [][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
531     if(splitKeys == null || splitKeys.length != numRegions - 1) {
532       throw new IllegalArgumentException("Unable to split key range into enough regions");
533     }
534     createTable(desc, splitKeys);
535   }
536 
537   /**
538    * Creates a new table with an initial set of empty regions defined by the
539    * specified split keys.  The total number of regions created will be the
540    * number of split keys plus one. Synchronous operation.
541    * Note : Avoid passing empty split key.
542    *
543    * @param desc table descriptor for table
544    * @param splitKeys array of split keys for the initial regions of the table
545    *
546    * @throws IllegalArgumentException if the table name is reserved, if the split keys
547    * are repeated and if the split key has empty byte array.
548    * @throws MasterNotRunningException if master is not running
549    * @throws org.apache.hadoop.hbase.TableExistsException if table already exists (If concurrent
550    * threads, the table may have been created between test-for-existence
551    * and attempt-at-creation).
552    * @throws IOException
553    */
554   @Override
555   public void createTable(final HTableDescriptor desc, byte [][] splitKeys)
556       throws IOException {
557     Future<Void> future = createTableAsyncV2(desc, splitKeys);
558     try {
559       // TODO: how long should we wait? spin forever?
560       future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
561     } catch (InterruptedException e) {
562       throw new InterruptedIOException("Interrupted when waiting" +
563           " for table to be enabled; meta scan was done");
564     } catch (TimeoutException e) {
565       throw new TimeoutIOException(e);
566     } catch (ExecutionException e) {
567       if (e.getCause() instanceof IOException) {
568         throw (IOException)e.getCause();
569       } else {
570         throw new IOException(e.getCause());
571       }
572     }
573   }
574 
575   /**
576    * Creates a new table but does not block and wait for it to come online.
577    * Asynchronous operation.  To check if the table exists, use
578    * {@link #isTableAvailable} -- it is not safe to create an HTable
579    * instance to this table before it is available.
580    * Note : Avoid passing empty split key.
581    * @param desc table descriptor for table
582    *
583    * @throws IllegalArgumentException Bad table name, if the split keys
584    * are repeated and if the split key has empty byte array.
585    * @throws MasterNotRunningException if master is not running
586    * @throws org.apache.hadoop.hbase.TableExistsException if table already exists (If concurrent
587    * threads, the table may have been created between test-for-existence
588    * and attempt-at-creation).
589    * @throws IOException
590    */
591   @Override
592   public void createTableAsync(final HTableDescriptor desc, final byte [][] splitKeys)
593       throws IOException {
594     createTableAsyncV2(desc, splitKeys);
595   }
596 
597   /**
598    * Creates a new table but does not block and wait for it to come online.
599    * You can use Future.get(long, TimeUnit) to wait on the operation to complete.
600    * It may throw ExecutionException if there was an error while executing the operation
601    * or TimeoutException in case the wait timeout was not long enough to allow the
602    * operation to complete.
603    *
604    * @param desc table descriptor for table
605    * @param splitKeys keys to check if the table has been created with all split keys
606    * @throws IllegalArgumentException Bad table name, if the split keys
607    *    are repeated and if the split key has empty byte array.
608    * @throws IOException if a remote or network exception occurs
609    * @return the result of the async creation. You can use Future.get(long, TimeUnit)
610    *    to wait on the operation to complete.
611    */
612   // TODO: This should be called Async but it will break binary compatibility
613   private Future<Void> createTableAsyncV2(final HTableDescriptor desc, final byte[][] splitKeys)
614       throws IOException {
615     if (desc.getTableName() == null) {
616       throw new IllegalArgumentException("TableName cannot be null");
617     }
618     if (splitKeys != null && splitKeys.length > 0) {
619       Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
620       // Verify there are no duplicate split keys
621       byte[] lastKey = null;
622       for (byte[] splitKey : splitKeys) {
623         if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
624           throw new IllegalArgumentException(
625               "Empty split key must not be passed in the split keys.");
626         }
627         if (lastKey != null && Bytes.equals(splitKey, lastKey)) {
628           throw new IllegalArgumentException("All split keys must be unique, " +
629             "found duplicate: " + Bytes.toStringBinary(splitKey) +
630             ", " + Bytes.toStringBinary(lastKey));
631         }
632         lastKey = splitKey;
633       }
634     }
635 
636     CreateTableResponse response = executeCallable(
637         new MasterCallable<CreateTableResponse>(getConnection()) {
638       @Override
639       public CreateTableResponse call(int callTimeout) throws ServiceException {
640         CreateTableRequest request = RequestConverter.buildCreateTableRequest(desc, splitKeys);
641         return master.createTable(null, request);
642       }
643     });
644     return new CreateTableFuture(this, desc, splitKeys, response);
645   }
646 
647   private static class CreateTableFuture extends ProcedureFuture<Void> {
648     private final HTableDescriptor desc;
649     private final byte[][] splitKeys;
650 
651     public CreateTableFuture(final HBaseAdmin admin, final HTableDescriptor desc,
652         final byte[][] splitKeys, final CreateTableResponse response) {
653       super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
654       this.splitKeys = splitKeys;
655       this.desc = desc;
656     }
657 
658     @Override
659     protected Void waitOperationResult(final long deadlineTs)
660         throws IOException, TimeoutException {
661       waitForTableEnabled(deadlineTs);
662       waitForAllRegionsOnline(deadlineTs);
663       return null;
664     }
665 
666     @Override
667     protected Void postOperationResult(final Void result, final long deadlineTs)
668         throws IOException, TimeoutException {
669       LOG.info("Created " + desc.getTableName());
670       return result;
671     }
672 
673     private void waitForTableEnabled(final long deadlineTs)
674         throws IOException, TimeoutException {
675       waitForState(deadlineTs, new WaitForStateCallable() {
676         @Override
677         public boolean checkState(int tries) throws IOException {
678           try {
679             if (getAdmin().isTableAvailable(desc.getTableName())) {
680               return true;
681             }
682           } catch (TableNotFoundException tnfe) {
683             LOG.debug("Table "+ desc.getTableName() +" was not enabled, sleeping. tries="+  tries);
684           }
685           return false;
686         }
687 
688         @Override
689         public void throwInterruptedException() throws InterruptedIOException {
690           throw new InterruptedIOException("Interrupted when waiting for table " +
691               desc.getTableName() + " to be enabled");
692         }
693 
694         @Override
695         public void throwTimeoutException(long elapsedTime) throws TimeoutException {
696           throw new TimeoutException("Table " + desc.getTableName() +
697             " not enabled after " + elapsedTime + "msec");
698         }
699       });
700     }
701 
702     private void waitForAllRegionsOnline(final long deadlineTs)
703         throws IOException, TimeoutException {
704       final AtomicInteger actualRegCount = new AtomicInteger(0);
705       final MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
706         @Override
707         public boolean processRow(Result rowResult) throws IOException {
708           RegionLocations list = MetaTableAccessor.getRegionLocations(rowResult);
709           if (list == null) {
710             LOG.warn("No serialized HRegionInfo in " + rowResult);
711             return true;
712           }
713           HRegionLocation l = list.getRegionLocation();
714           if (l == null) {
715             return true;
716           }
717           if (!l.getRegionInfo().getTable().equals(desc.getTableName())) {
718             return false;
719           }
720           if (l.getRegionInfo().isOffline() || l.getRegionInfo().isSplit()) return true;
721           HRegionLocation[] locations = list.getRegionLocations();
722           for (HRegionLocation location : locations) {
723             if (location == null) continue;
724             ServerName serverName = location.getServerName();
725             // Make sure that regions are assigned to server
726             if (serverName != null && serverName.getHostAndPort() != null) {
727               actualRegCount.incrementAndGet();
728             }
729           }
730           return true;
731         }
732       };
733 
734       int tries = 0;
735       IOException serverEx = null;
736       int numRegs = (splitKeys == null ? 1 : splitKeys.length + 1) * desc.getRegionReplication();
737       while (EnvironmentEdgeManager.currentTime() < deadlineTs) {
738         actualRegCount.set(0);
739         MetaScanner.metaScan(getAdmin().getConnection(), visitor, desc.getTableName());
740         if (actualRegCount.get() == numRegs) {
741           // all the regions are online
742           return;
743         }
744 
745         try {
746           Thread.sleep(getAdmin().getPauseTime(tries++));
747         } catch (InterruptedException e) {
748           throw new InterruptedIOException("Interrupted when opening" +
749             " regions; " + actualRegCount.get() + " of " + numRegs +
750             " regions processed so far");
751         }
752       }
753       throw new TimeoutException("Only " + actualRegCount.get() +
754               " of " + numRegs + " regions are online; retries exhausted.");
755     }
756   }
757 
758   public void deleteTable(final String tableName) throws IOException {
759     deleteTable(TableName.valueOf(tableName));
760   }
761 
762   public void deleteTable(final byte[] tableName) throws IOException {
763     deleteTable(TableName.valueOf(tableName));
764   }
765 
766   /**
767    * Deletes a table.
768    * Synchronous operation.
769    *
770    * @param tableName name of table to delete
771    * @throws IOException if a remote or network exception occurs
772    */
773   @Override
774   public void deleteTable(final TableName tableName) throws IOException {
775     Future<Void> future = deleteTableAsyncV2(tableName);
776     try {
777       future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
778     } catch (InterruptedException e) {
779       throw new InterruptedIOException("Interrupted when waiting for table to be deleted");
780     } catch (TimeoutException e) {
781       throw new TimeoutIOException(e);
782     } catch (ExecutionException e) {
783       if (e.getCause() instanceof IOException) {
784         throw (IOException)e.getCause();
785       } else {
786         throw new IOException(e.getCause());
787       }
788     }
789   }
790 
791   /**
792    * Deletes the table but does not block and wait for it be completely removed.
793    * You can use Future.get(long, TimeUnit) to wait on the operation to complete.
794    * It may throw ExecutionException if there was an error while executing the operation
795    * or TimeoutException in case the wait timeout was not long enough to allow the
796    * operation to complete.
797    *
798    * @param desc table descriptor for table
799    * @param tableName name of table to delete
800    * @throws IOException if a remote or network exception occurs
801    * @return the result of the async delete. You can use Future.get(long, TimeUnit)
802    *    to wait on the operation to complete.
803    */
804   // TODO: This should be called Async but it will break binary compatibility
805   private Future<Void> deleteTableAsyncV2(final TableName tableName) throws IOException {
806     DeleteTableResponse response = executeCallable(
807         new MasterCallable<DeleteTableResponse>(getConnection()) {
808       @Override
809       public DeleteTableResponse call(int callTimeout) throws ServiceException {
810         DeleteTableRequest req = RequestConverter.buildDeleteTableRequest(tableName);
811         return master.deleteTable(null,req);
812       }
813     });
814     return new DeleteTableFuture(this, tableName, response);
815   }
816 
817   private static class DeleteTableFuture extends ProcedureFuture<Void> {
818     private final TableName tableName;
819 
820     public DeleteTableFuture(final HBaseAdmin admin, final TableName tableName,
821         final DeleteTableResponse response) {
822       super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
823       this.tableName = tableName;
824     }
825 
826     @Override
827     protected Void waitOperationResult(final long deadlineTs)
828         throws IOException, TimeoutException {
829       waitTableNotFound(deadlineTs);
830       return null;
831     }
832 
833     @Override
834     protected Void postOperationResult(final Void result, final long deadlineTs)
835         throws IOException, TimeoutException {
836       // Delete cached information to prevent clients from using old locations
837       getAdmin().getConnection().clearRegionCache(tableName);
838       LOG.info("Deleted " + tableName);
839       return result;
840     }
841 
842     private void waitTableNotFound(final long deadlineTs)
843         throws IOException, TimeoutException {
844       waitForState(deadlineTs, new WaitForStateCallable() {
845         @Override
846         public boolean checkState(int tries) throws IOException {
847           return !getAdmin().tableExists(tableName);
848         }
849 
850         @Override
851         public void throwInterruptedException() throws InterruptedIOException {
852           throw new InterruptedIOException("Interrupted when waiting for table to be deleted");
853         }
854 
855         @Override
856         public void throwTimeoutException(long elapsedTime) throws TimeoutException {
857           throw new TimeoutException("Table " + tableName + " not yet deleted after " +
858               elapsedTime + "msec");
859         }
860       });
861     }
862   }
863 
864   /**
865    * Deletes tables matching the passed in pattern and wait on completion.
866    *
867    * Warning: Use this method carefully, there is no prompting and the effect is
868    * immediate. Consider using {@link #listTables(java.lang.String)} and
869    * {@link #deleteTable(byte[])}
870    *
871    * @param regex The regular expression to match table names against
872    * @return Table descriptors for tables that couldn't be deleted
873    * @throws IOException
874    * @see #deleteTables(java.util.regex.Pattern)
875    * @see #deleteTable(java.lang.String)
876    */
877   @Override
878   public HTableDescriptor[] deleteTables(String regex) throws IOException {
879     return deleteTables(Pattern.compile(regex));
880   }
881 
882   /**
883    * Delete tables matching the passed in pattern and wait on completion.
884    *
885    * Warning: Use this method carefully, there is no prompting and the effect is
886    * immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
887    * {@link #deleteTable(byte[])}
888    *
889    * @param pattern The pattern to match table names against
890    * @return Table descriptors for tables that couldn't be deleted
891    * @throws IOException
892    */
893   @Override
894   public HTableDescriptor[] deleteTables(Pattern pattern) throws IOException {
895     List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
896     for (HTableDescriptor table : listTables(pattern)) {
897       try {
898         deleteTable(table.getTableName());
899       } catch (IOException ex) {
900         LOG.info("Failed to delete table " + table.getTableName(), ex);
901         failed.add(table);
902       }
903     }
904     return failed.toArray(new HTableDescriptor[failed.size()]);
905   }
906 
907   /**
908    * Truncate a table.
909    * Synchronous operation.
910    *
911    * @param tableName name of table to truncate
912    * @param preserveSplits True if the splits should be preserved
913    * @throws IOException if a remote or network exception occurs
914    */
915   @Override
916   public void truncateTable(final TableName tableName, final boolean preserveSplits)
917       throws IOException {
918     executeCallable(new MasterCallable<Void>(getConnection()) {
919       @Override
920       public Void call(int callTimeout) throws ServiceException {
921         TruncateTableRequest req = RequestConverter.buildTruncateTableRequest(
922           tableName, preserveSplits);
923         master.truncateTable(null, req);
924         return null;
925       }
926     });
927   }
928 
929   /**
930    * Enable a table.  May timeout.  Use {@link #enableTableAsync(byte[])}
931    * and {@link #isTableEnabled(byte[])} instead.
932    * The table has to be in disabled state for it to be enabled.
933    * @param tableName name of the table
934    * @throws IOException if a remote or network exception occurs
935    * There could be couple types of IOException
936    * TableNotFoundException means the table doesn't exist.
937    * TableNotDisabledException means the table isn't in disabled state.
938    * @see #isTableEnabled(byte[])
939    * @see #disableTable(byte[])
940    * @see #enableTableAsync(byte[])
941    */
942   @Override
943   public void enableTable(final TableName tableName)
944   throws IOException {
945     Future<Void> future = enableTableAsyncV2(tableName);
946     try {
947       future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
948     } catch (InterruptedException e) {
949       throw new InterruptedIOException("Interrupted when waiting for table to be disabled");
950     } catch (TimeoutException e) {
951       throw new TimeoutIOException(e);
952     } catch (ExecutionException e) {
953       if (e.getCause() instanceof IOException) {
954         throw (IOException)e.getCause();
955       } else {
956         throw new IOException(e.getCause());
957       }
958     }
959   }
960 
961   public void enableTable(final byte[] tableName)
962   throws IOException {
963     enableTable(TableName.valueOf(tableName));
964   }
965 
966   public void enableTable(final String tableName)
967   throws IOException {
968     enableTable(TableName.valueOf(tableName));
969   }
970 
971   /**
972    * Wait for the table to be enabled and available
973    * If enabling the table exceeds the retry period, an exception is thrown.
974    * @param tableName name of the table
975    * @throws IOException if a remote or network exception occurs or
976    *    table is not enabled after the retries period.
977    */
978   private void waitUntilTableIsEnabled(final TableName tableName) throws IOException {
979     boolean enabled = false;
980     long start = EnvironmentEdgeManager.currentTime();
981     for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
982       try {
983         enabled = isTableEnabled(tableName);
984       } catch (TableNotFoundException tnfe) {
985         // wait for table to be created
986         enabled = false;
987       }
988       enabled = enabled && isTableAvailable(tableName);
989       if (enabled) {
990         break;
991       }
992       long sleep = getPauseTime(tries);
993       if (LOG.isDebugEnabled()) {
994         LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
995           "enabled in " + tableName);
996       }
997       try {
998         Thread.sleep(sleep);
999       } catch (InterruptedException e) {
1000         // Do this conversion rather than let it out because do not want to
1001         // change the method signature.
1002         throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
1003       }
1004     }
1005     if (!enabled) {
1006       long msec = EnvironmentEdgeManager.currentTime() - start;
1007       throw new IOException("Table '" + tableName +
1008         "' not yet enabled, after " + msec + "ms.");
1009     }
1010   }
1011 
1012   /**
1013    * Brings a table on-line (enables it).  Method returns immediately though
1014    * enable of table may take some time to complete, especially if the table
1015    * is large (All regions are opened as part of enabling process).  Check
1016    * {@link #isTableEnabled(byte[])} to learn when table is fully online.  If
1017    * table is taking too long to online, check server logs.
1018    * @param tableName
1019    * @throws IOException
1020    * @since 0.90.0
1021    */
1022   @Override
1023   public void enableTableAsync(final TableName tableName)
1024   throws IOException {
1025     enableTableAsyncV2(tableName);
1026   }
1027 
1028   public void enableTableAsync(final byte[] tableName)
1029   throws IOException {
1030     enableTable(TableName.valueOf(tableName));
1031   }
1032 
1033   public void enableTableAsync(final String tableName)
1034   throws IOException {
1035     enableTableAsync(TableName.valueOf(tableName));
1036   }
1037 
1038   /**
1039    * Enable the table but does not block and wait for it be completely enabled.
1040    * You can use Future.get(long, TimeUnit) to wait on the operation to complete.
1041    * It may throw ExecutionException if there was an error while executing the operation
1042    * or TimeoutException in case the wait timeout was not long enough to allow the
1043    * operation to complete.
1044    *
1045    * @param tableName name of table to delete
1046    * @throws IOException if a remote or network exception occurs
1047    * @return the result of the async enable. You can use Future.get(long, TimeUnit)
1048    *    to wait on the operation to complete.
1049    */
1050   // TODO: This should be called Async but it will break binary compatibility
1051   private Future<Void> enableTableAsyncV2(final TableName tableName) throws IOException {
1052     TableName.isLegalFullyQualifiedTableName(tableName.getName());
1053     EnableTableResponse response = executeCallable(
1054         new MasterCallable<EnableTableResponse>(getConnection()) {
1055       @Override
1056       public EnableTableResponse call(int callTimeout) throws ServiceException {
1057         LOG.info("Started enable of " + tableName);
1058         EnableTableRequest req = RequestConverter.buildEnableTableRequest(tableName);
1059         return master.enableTable(null,req);
1060       }
1061     });
1062     return new EnableTableFuture(this, tableName, response);
1063   }
1064 
1065   private static class EnableTableFuture extends ProcedureFuture<Void> {
1066     private final TableName tableName;
1067 
1068     public EnableTableFuture(final HBaseAdmin admin, final TableName tableName,
1069         final EnableTableResponse response) {
1070       super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
1071       this.tableName = tableName;
1072     }
1073 
1074     @Override
1075     protected Void waitOperationResult(final long deadlineTs)
1076         throws IOException, TimeoutException {
1077       waitTableEnabled(deadlineTs);
1078       return null;
1079     }
1080 
1081     @Override
1082     protected Void postOperationResult(final Void result, final long deadlineTs)
1083         throws IOException, TimeoutException {
1084       LOG.info("Enabled " + tableName);
1085       return result;
1086     }
1087 
1088     private void waitTableEnabled(final long deadlineTs)
1089         throws IOException, TimeoutException {
1090       waitForState(deadlineTs, new WaitForStateCallable() {
1091         @Override
1092         public boolean checkState(int tries) throws IOException {
1093           boolean enabled;
1094           try {
1095             enabled = getAdmin().isTableEnabled(tableName);
1096           } catch (TableNotFoundException tnfe) {
1097             return false;
1098           }
1099           return enabled && getAdmin().isTableAvailable(tableName);
1100         }
1101 
1102         @Override
1103         public void throwInterruptedException() throws InterruptedIOException {
1104           throw new InterruptedIOException("Interrupted when waiting for table to be enabled");
1105         }
1106 
1107         @Override
1108         public void throwTimeoutException(long elapsedTime) throws TimeoutException {
1109           throw new TimeoutException("Table " + tableName + " not yet enabled after " +
1110               elapsedTime + "msec");
1111         }
1112       });
1113     }
1114   }
1115 
1116   /**
1117    * Enable tables matching the passed in pattern and wait on completion.
1118    *
1119    * Warning: Use this method carefully, there is no prompting and the effect is
1120    * immediate. Consider using {@link #listTables(java.lang.String)} and
1121    * {@link #enableTable(byte[])}
1122    *
1123    * @param regex The regular expression to match table names against
1124    * @throws IOException
1125    * @see #enableTables(java.util.regex.Pattern)
1126    * @see #enableTable(java.lang.String)
1127    */
1128   @Override
1129   public HTableDescriptor[] enableTables(String regex) throws IOException {
1130     return enableTables(Pattern.compile(regex));
1131   }
1132 
1133   /**
1134    * Enable tables matching the passed in pattern and wait on completion.
1135    *
1136    * Warning: Use this method carefully, there is no prompting and the effect is
1137    * immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
1138    * {@link #enableTable(byte[])}
1139    *
1140    * @param pattern The pattern to match table names against
1141    * @throws IOException
1142    */
1143   @Override
1144   public HTableDescriptor[] enableTables(Pattern pattern) throws IOException {
1145     List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
1146     for (HTableDescriptor table : listTables(pattern)) {
1147       if (isTableDisabled(table.getTableName())) {
1148         try {
1149           enableTable(table.getTableName());
1150         } catch (IOException ex) {
1151           LOG.info("Failed to enable table " + table.getTableName(), ex);
1152           failed.add(table);
1153         }
1154       }
1155     }
1156     return failed.toArray(new HTableDescriptor[failed.size()]);
1157   }
1158 
1159   /**
1160    * Starts the disable of a table.  If it is being served, the master
1161    * will tell the servers to stop serving it.  This method returns immediately.
1162    * The disable of a table can take some time if the table is large (all
1163    * regions are closed as part of table disable operation).
1164    * Call {@link #isTableDisabled(byte[])} to check for when disable completes.
1165    * If table is taking too long to online, check server logs.
1166    * @param tableName name of table
1167    * @throws IOException if a remote or network exception occurs
1168    * @see #isTableDisabled(byte[])
1169    * @see #isTableEnabled(byte[])
1170    * @since 0.90.0
1171    */
1172   @Override
1173   public void disableTableAsync(final TableName tableName) throws IOException {
1174     disableTableAsyncV2(tableName);
1175   }
1176 
1177   public void disableTableAsync(final byte[] tableName) throws IOException {
1178     disableTableAsync(TableName.valueOf(tableName));
1179   }
1180 
1181   public void disableTableAsync(final String tableName) throws IOException {
1182     disableTableAsync(TableName.valueOf(tableName));
1183   }
1184 
1185   /**
1186    * Disable table and wait on completion.  May timeout eventually.  Use
1187    * {@link #disableTableAsync(byte[])} and {@link #isTableDisabled(String)}
1188    * instead.
1189    * The table has to be in enabled state for it to be disabled.
1190    * @param tableName
1191    * @throws IOException
1192    * There could be couple types of IOException
1193    * TableNotFoundException means the table doesn't exist.
1194    * TableNotEnabledException means the table isn't in enabled state.
1195    */
1196   @Override
1197   public void disableTable(final TableName tableName)
1198   throws IOException {
1199     Future<Void> future = disableTableAsyncV2(tableName);
1200     try {
1201       future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
1202     } catch (InterruptedException e) {
1203       throw new InterruptedIOException("Interrupted when waiting for table to be disabled");
1204     } catch (TimeoutException e) {
1205       throw new TimeoutIOException(e);
1206     } catch (ExecutionException e) {
1207       if (e.getCause() instanceof IOException) {
1208         throw (IOException)e.getCause();
1209       } else {
1210         throw new IOException(e.getCause());
1211       }
1212     }
1213   }
1214 
1215   public void disableTable(final byte[] tableName)
1216   throws IOException {
1217     disableTable(TableName.valueOf(tableName));
1218   }
1219 
1220   public void disableTable(final String tableName)
1221   throws IOException {
1222     disableTable(TableName.valueOf(tableName));
1223   }
1224 
1225   /**
1226    * Disable the table but does not block and wait for it be completely disabled.
1227    * You can use Future.get(long, TimeUnit) to wait on the operation to complete.
1228    * It may throw ExecutionException if there was an error while executing the operation
1229    * or TimeoutException in case the wait timeout was not long enough to allow the
1230    * operation to complete.
1231    *
1232    * @param tableName name of table to delete
1233    * @throws IOException if a remote or network exception occurs
1234    * @return the result of the async disable. You can use Future.get(long, TimeUnit)
1235    *    to wait on the operation to complete.
1236    */
1237   // TODO: This should be called Async but it will break binary compatibility
1238   private Future<Void> disableTableAsyncV2(final TableName tableName) throws IOException {
1239     TableName.isLegalFullyQualifiedTableName(tableName.getName());
1240     DisableTableResponse response = executeCallable(
1241         new MasterCallable<DisableTableResponse>(getConnection()) {
1242       @Override
1243       public DisableTableResponse call(int callTimeout) throws ServiceException {
1244         LOG.info("Started disable of " + tableName);
1245         DisableTableRequest req = RequestConverter.buildDisableTableRequest(tableName);
1246         return master.disableTable(null, req);
1247       }
1248     });
1249     return new DisableTableFuture(this, tableName, response);
1250   }
1251 
1252   private static class DisableTableFuture extends ProcedureFuture<Void> {
1253     private final TableName tableName;
1254 
1255     public DisableTableFuture(final HBaseAdmin admin, final TableName tableName,
1256         final DisableTableResponse response) {
1257       super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
1258       this.tableName = tableName;
1259     }
1260 
1261     @Override
1262     protected Void waitOperationResult(final long deadlineTs)
1263         throws IOException, TimeoutException {
1264       waitTableDisabled(deadlineTs);
1265       return null;
1266     }
1267 
1268     @Override
1269     protected Void postOperationResult(final Void result, final long deadlineTs)
1270         throws IOException, TimeoutException {
1271       LOG.info("Disabled " + tableName);
1272       return result;
1273     }
1274 
1275     private void waitTableDisabled(final long deadlineTs)
1276         throws IOException, TimeoutException {
1277       waitForState(deadlineTs, new WaitForStateCallable() {
1278         @Override
1279         public boolean checkState(int tries) throws IOException {
1280           return getAdmin().isTableDisabled(tableName);
1281         }
1282 
1283         @Override
1284         public void throwInterruptedException() throws InterruptedIOException {
1285           throw new InterruptedIOException("Interrupted when waiting for table to be disabled");
1286         }
1287 
1288         @Override
1289         public void throwTimeoutException(long elapsedTime) throws TimeoutException {
1290           throw new TimeoutException("Table " + tableName + " not yet disabled after " +
1291               elapsedTime + "msec");
1292         }
1293       });
1294     }
1295   }
1296 
1297   /**
1298    * Disable tables matching the passed in pattern and wait on completion.
1299    *
1300    * Warning: Use this method carefully, there is no prompting and the effect is
1301    * immediate. Consider using {@link #listTables(java.lang.String)} and
1302    * {@link #disableTable(byte[])}
1303    *
1304    * @param regex The regular expression to match table names against
1305    * @return Table descriptors for tables that couldn't be disabled
1306    * @throws IOException
1307    * @see #disableTables(java.util.regex.Pattern)
1308    * @see #disableTable(java.lang.String)
1309    */
1310   @Override
1311   public HTableDescriptor[] disableTables(String regex) throws IOException {
1312     return disableTables(Pattern.compile(regex));
1313   }
1314 
1315   /**
1316    * Disable tables matching the passed in pattern and wait on completion.
1317    *
1318    * Warning: Use this method carefully, there is no prompting and the effect is
1319    * immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
1320    * {@link #disableTable(byte[])}
1321    *
1322    * @param pattern The pattern to match table names against
1323    * @return Table descriptors for tables that couldn't be disabled
1324    * @throws IOException
1325    */
1326   @Override
1327   public HTableDescriptor[] disableTables(Pattern pattern) throws IOException {
1328     List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
1329     for (HTableDescriptor table : listTables(pattern)) {
1330       if (isTableEnabled(table.getTableName())) {
1331         try {
1332           disableTable(table.getTableName());
1333         } catch (IOException ex) {
1334           LOG.info("Failed to disable table " + table.getTableName(), ex);
1335           failed.add(table);
1336         }
1337       }
1338     }
1339     return failed.toArray(new HTableDescriptor[failed.size()]);
1340   }
1341 
1342   /*
1343    * Checks whether table exists. If not, throws TableNotFoundException
1344    * @param tableName
1345    */
1346   private void checkTableExistence(TableName tableName) throws IOException {
1347     if (!tableExists(tableName)) {
1348       throw new TableNotFoundException(tableName);
1349     }
1350   }
1351 
1352   /**
1353    * @param tableName name of table to check
1354    * @return true if table is on-line
1355    * @throws IOException if a remote or network exception occurs
1356    */
1357   @Override
1358   public boolean isTableEnabled(TableName tableName) throws IOException {
1359     checkTableExistence(tableName);
1360     return connection.isTableEnabled(tableName);
1361   }
1362 
1363   public boolean isTableEnabled(byte[] tableName) throws IOException {
1364     return isTableEnabled(TableName.valueOf(tableName));
1365   }
1366 
1367   public boolean isTableEnabled(String tableName) throws IOException {
1368     return isTableEnabled(TableName.valueOf(tableName));
1369   }
1370 
1371 
1372 
1373   /**
1374    * @param tableName name of table to check
1375    * @return true if table is off-line
1376    * @throws IOException if a remote or network exception occurs
1377    */
1378   @Override
1379   public boolean isTableDisabled(TableName tableName) throws IOException {
1380     checkTableExistence(tableName);
1381     return connection.isTableDisabled(tableName);
1382   }
1383 
1384   public boolean isTableDisabled(byte[] tableName) throws IOException {
1385     return isTableDisabled(TableName.valueOf(tableName));
1386   }
1387 
1388   public boolean isTableDisabled(String tableName) throws IOException {
1389     return isTableDisabled(TableName.valueOf(tableName));
1390   }
1391 
1392   /**
1393    * @param tableName name of table to check
1394    * @return true if all regions of the table are available
1395    * @throws IOException if a remote or network exception occurs
1396    */
1397   @Override
1398   public boolean isTableAvailable(TableName tableName) throws IOException {
1399     return connection.isTableAvailable(tableName);
1400   }
1401 
1402   public boolean isTableAvailable(byte[] tableName) throws IOException {
1403     return isTableAvailable(TableName.valueOf(tableName));
1404   }
1405 
1406   public boolean isTableAvailable(String tableName) throws IOException {
1407     return isTableAvailable(TableName.valueOf(tableName));
1408   }
1409 
1410   /**
1411    * Use this api to check if the table has been created with the specified number of
1412    * splitkeys which was used while creating the given table.
1413    * Note : If this api is used after a table's region gets splitted, the api may return
1414    * false.
1415    * @param tableName
1416    *          name of table to check
1417    * @param splitKeys
1418    *          keys to check if the table has been created with all split keys
1419    * @throws IOException
1420    *           if a remote or network excpetion occurs
1421    */
1422   @Override
1423   public boolean isTableAvailable(TableName tableName,
1424                                   byte[][] splitKeys) throws IOException {
1425     return connection.isTableAvailable(tableName, splitKeys);
1426   }
1427 
1428   public boolean isTableAvailable(byte[] tableName,
1429                                   byte[][] splitKeys) throws IOException {
1430     return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1431   }
1432 
1433   public boolean isTableAvailable(String tableName,
1434                                   byte[][] splitKeys) throws IOException {
1435     return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1436   }
1437 
1438   /**
1439    * Get the status of alter command - indicates how many regions have received
1440    * the updated schema Asynchronous operation.
1441    *
1442    * @param tableName TableName instance
1443    * @return Pair indicating the number of regions updated Pair.getFirst() is the
1444    *         regions that are yet to be updated Pair.getSecond() is the total number
1445    *         of regions of the table
1446    * @throws IOException
1447    *           if a remote or network exception occurs
1448    */
1449   @Override
1450   public Pair<Integer, Integer> getAlterStatus(final TableName tableName)
1451   throws IOException {
1452     return executeCallable(new MasterCallable<Pair<Integer, Integer>>(getConnection()) {
1453       @Override
1454       public Pair<Integer, Integer> call(int callTimeout) throws ServiceException {
1455         GetSchemaAlterStatusRequest req = RequestConverter
1456             .buildGetSchemaAlterStatusRequest(tableName);
1457         GetSchemaAlterStatusResponse ret = master.getSchemaAlterStatus(null, req);
1458         Pair<Integer, Integer> pair = new Pair<Integer, Integer>(Integer.valueOf(ret
1459             .getYetToUpdateRegions()), Integer.valueOf(ret.getTotalRegions()));
1460         return pair;
1461       }
1462     });
1463   }
1464 
1465   /**
1466    * Get the status of alter command - indicates how many regions have received
1467    * the updated schema Asynchronous operation.
1468    *
1469    * @param tableName
1470    *          name of the table to get the status of
1471    * @return Pair indicating the number of regions updated Pair.getFirst() is the
1472    *         regions that are yet to be updated Pair.getSecond() is the total number
1473    *         of regions of the table
1474    * @throws IOException
1475    *           if a remote or network exception occurs
1476    */
1477   @Override
1478   public Pair<Integer, Integer> getAlterStatus(final byte[] tableName)
1479    throws IOException {
1480     return getAlterStatus(TableName.valueOf(tableName));
1481   }
1482 
1483   /**
1484    * Add a column to an existing table.
1485    * Asynchronous operation.
1486    *
1487    * @param tableName name of the table to add column to
1488    * @param column column descriptor of column to be added
1489    * @throws IOException if a remote or network exception occurs
1490    */
1491   public void addColumn(final byte[] tableName, HColumnDescriptor column)
1492   throws IOException {
1493     addColumn(TableName.valueOf(tableName), column);
1494   }
1495 
1496 
1497   /**
1498    * Add a column to an existing table.
1499    * Asynchronous operation.
1500    *
1501    * @param tableName name of the table to add column to
1502    * @param column column descriptor of column to be added
1503    * @throws IOException if a remote or network exception occurs
1504    */
1505   public void addColumn(final String tableName, HColumnDescriptor column)
1506   throws IOException {
1507     addColumn(TableName.valueOf(tableName), column);
1508   }
1509 
1510   /**
1511    * Add a column to an existing table.
1512    * Asynchronous operation.
1513    *
1514    * @param tableName name of the table to add column to
1515    * @param column column descriptor of column to be added
1516    * @throws IOException if a remote or network exception occurs
1517    */
1518   @Override
1519   public void addColumn(final TableName tableName, final HColumnDescriptor column)
1520   throws IOException {
1521     executeCallable(new MasterCallable<Void>(getConnection()) {
1522       @Override
1523       public Void call(int callTimeout) throws ServiceException {
1524         AddColumnRequest req = RequestConverter.buildAddColumnRequest(tableName, column);
1525         master.addColumn(null,req);
1526         return null;
1527       }
1528     });
1529   }
1530 
1531   /**
1532    * Delete a column from a table.
1533    * Asynchronous operation.
1534    *
1535    * @param tableName name of table
1536    * @param columnName name of column to be deleted
1537    * @throws IOException if a remote or network exception occurs
1538    */
1539   public void deleteColumn(final byte[] tableName, final String columnName)
1540   throws IOException {
1541     deleteColumn(TableName.valueOf(tableName), Bytes.toBytes(columnName));
1542   }
1543 
1544   /**
1545    * Delete a column from a table.
1546    * Asynchronous operation.
1547    *
1548    * @param tableName name of table
1549    * @param columnName name of column to be deleted
1550    * @throws IOException if a remote or network exception occurs
1551    */
1552   public void deleteColumn(final String tableName, final String columnName)
1553   throws IOException {
1554     deleteColumn(TableName.valueOf(tableName), Bytes.toBytes(columnName));
1555   }
1556 
1557   /**
1558    * Delete a column from a table.
1559    * Asynchronous operation.
1560    *
1561    * @param tableName name of table
1562    * @param columnName name of column to be deleted
1563    * @throws IOException if a remote or network exception occurs
1564    */
1565   @Override
1566   public void deleteColumn(final TableName tableName, final byte [] columnName)
1567   throws IOException {
1568     executeCallable(new MasterCallable<Void>(getConnection()) {
1569       @Override
1570       public Void call(int callTimeout) throws ServiceException {
1571         DeleteColumnRequest req = RequestConverter.buildDeleteColumnRequest(tableName, columnName);
1572         master.deleteColumn(null,req);
1573         return null;
1574       }
1575     });
1576   }
1577 
1578   /**
1579    * Modify an existing column family on a table.
1580    * Asynchronous operation.
1581    *
1582    * @param tableName name of table
1583    * @param descriptor new column descriptor to use
1584    * @throws IOException if a remote or network exception occurs
1585    */
1586   public void modifyColumn(final String tableName, HColumnDescriptor descriptor)
1587   throws IOException {
1588     modifyColumn(TableName.valueOf(tableName), descriptor);
1589   }
1590 
1591   /**
1592    * Modify an existing column family on a table.
1593    * Asynchronous operation.
1594    *
1595    * @param tableName name of table
1596    * @param descriptor new column descriptor to use
1597    * @throws IOException if a remote or network exception occurs
1598    */
1599   public void modifyColumn(final byte[] tableName, HColumnDescriptor descriptor)
1600   throws IOException {
1601     modifyColumn(TableName.valueOf(tableName), descriptor);
1602   }
1603 
1604 
1605 
1606   /**
1607    * Modify an existing column family on a table.
1608    * Asynchronous operation.
1609    *
1610    * @param tableName name of table
1611    * @param descriptor new column descriptor to use
1612    * @throws IOException if a remote or network exception occurs
1613    */
1614   @Override
1615   public void modifyColumn(final TableName tableName, final HColumnDescriptor descriptor)
1616   throws IOException {
1617     executeCallable(new MasterCallable<Void>(getConnection()) {
1618       @Override
1619       public Void call(int callTimeout) throws ServiceException {
1620         ModifyColumnRequest req = RequestConverter.buildModifyColumnRequest(tableName, descriptor);
1621         master.modifyColumn(null,req);
1622         return null;
1623       }
1624     });
1625   }
1626 
1627   /**
1628    * Close a region. For expert-admins.  Runs close on the regionserver.  The
1629    * master will not be informed of the close.
1630    * @param regionname region name to close
1631    * @param serverName If supplied, we'll use this location rather than
1632    * the one currently in <code>hbase:meta</code>
1633    * @throws IOException if a remote or network exception occurs
1634    */
1635   @Override
1636   public void closeRegion(final String regionname, final String serverName)
1637   throws IOException {
1638     closeRegion(Bytes.toBytes(regionname), serverName);
1639   }
1640 
1641   /**
1642    * Close a region.  For expert-admins  Runs close on the regionserver.  The
1643    * master will not be informed of the close.
1644    * @param regionname region name to close
1645    * @param serverName The servername of the regionserver.  If passed null we
1646    * will use servername found in the hbase:meta table. A server name
1647    * is made of host, port and startcode.  Here is an example:
1648    * <code> host187.example.com,60020,1289493121758</code>
1649    * @throws IOException if a remote or network exception occurs
1650    */
1651   @Override
1652   public void closeRegion(final byte [] regionname, final String serverName)
1653       throws IOException {
1654     if (serverName != null) {
1655       Pair<HRegionInfo, ServerName> pair = MetaTableAccessor.getRegion(connection, regionname);
1656       if (pair == null || pair.getFirst() == null) {
1657         throw new UnknownRegionException(Bytes.toStringBinary(regionname));
1658       } else {
1659         closeRegion(ServerName.valueOf(serverName), pair.getFirst());
1660       }
1661     } else {
1662       Pair<HRegionInfo, ServerName> pair = MetaTableAccessor.getRegion(connection, regionname);
1663       if (pair == null) {
1664         throw new UnknownRegionException(Bytes.toStringBinary(regionname));
1665       } else if (pair.getSecond() == null) {
1666         throw new NoServerForRegionException(Bytes.toStringBinary(regionname));
1667       } else {
1668         closeRegion(pair.getSecond(), pair.getFirst());
1669       }
1670     }
1671   }
1672 
1673   /**
1674    * For expert-admins. Runs close on the regionserver. Closes a region based on
1675    * the encoded region name. The region server name is mandatory. If the
1676    * servername is provided then based on the online regions in the specified
1677    * regionserver the specified region will be closed. The master will not be
1678    * informed of the close. Note that the regionname is the encoded regionname.
1679    *
1680    * @param encodedRegionName
1681    *          The encoded region name; i.e. the hash that makes up the region
1682    *          name suffix: e.g. if regionname is
1683    *          <code>TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396.</code>
1684    *          , then the encoded region name is:
1685    *          <code>527db22f95c8a9e0116f0cc13c680396</code>.
1686    * @param serverName
1687    *          The servername of the regionserver. A server name is made of host,
1688    *          port and startcode. This is mandatory. Here is an example:
1689    *          <code> host187.example.com,60020,1289493121758</code>
1690    * @return true if the region was closed, false if not.
1691    * @throws IOException
1692    *           if a remote or network exception occurs
1693    */
1694   @Override
1695   public boolean closeRegionWithEncodedRegionName(final String encodedRegionName,
1696       final String serverName) throws IOException {
1697     if (null == serverName || ("").equals(serverName.trim())) {
1698       throw new IllegalArgumentException(
1699           "The servername cannot be null or empty.");
1700     }
1701     ServerName sn = ServerName.valueOf(serverName);
1702     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1703     // Close the region without updating zk state.
1704     CloseRegionRequest request =
1705       RequestConverter.buildCloseRegionRequest(sn, encodedRegionName, false);
1706     try {
1707       CloseRegionResponse response = admin.closeRegion(null, request);
1708       boolean isRegionClosed = response.getClosed();
1709       if (false == isRegionClosed) {
1710         LOG.error("Not able to close the region " + encodedRegionName + ".");
1711       }
1712       return isRegionClosed;
1713     } catch (ServiceException se) {
1714       throw ProtobufUtil.getRemoteException(se);
1715     }
1716   }
1717 
1718   /**
1719    * Close a region.  For expert-admins  Runs close on the regionserver.  The
1720    * master will not be informed of the close.
1721    * @param sn
1722    * @param hri
1723    * @throws IOException
1724    */
1725   @Override
1726   public void closeRegion(final ServerName sn, final HRegionInfo hri)
1727   throws IOException {
1728     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1729     // Close the region without updating zk state.
1730     ProtobufUtil.closeRegion(admin, sn, hri.getRegionName(), false);
1731   }
1732 
1733   /**
1734    * Get all the online regions on a region server.
1735    */
1736   @Override
1737   public List<HRegionInfo> getOnlineRegions(final ServerName sn) throws IOException {
1738     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1739     return ProtobufUtil.getOnlineRegions(admin);
1740   }
1741 
1742   /**
1743    * {@inheritDoc}
1744    */
1745   @Override
1746   public void flush(final TableName tableName) throws IOException {
1747     checkTableExists(tableName);
1748     if (isTableDisabled(tableName)) {
1749       LOG.info("Table is disabled: " + tableName.getNameAsString());
1750       return;
1751     }
1752     execProcedure("flush-table-proc", tableName.getNameAsString(),
1753       new HashMap<String, String>());
1754   }
1755 
1756   /**
1757    * {@inheritDoc}
1758    */
1759   @Override
1760   public void flushRegion(final byte[] regionName) throws IOException {
1761     Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
1762     if (regionServerPair == null) {
1763       throw new IllegalArgumentException("Unknown regionname: " + Bytes.toStringBinary(regionName));
1764     }
1765     if (regionServerPair.getSecond() == null) {
1766       throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
1767     }
1768     flush(regionServerPair.getSecond(), regionServerPair.getFirst());
1769   }
1770 
1771   /**
1772    * @deprecated Use {@link #flush(org.apache.hadoop.hbase.TableName)} or {@link #flushRegion
1773    * (byte[])} instead.
1774    */
1775   @Deprecated
1776   public void flush(final String tableNameOrRegionName)
1777   throws IOException, InterruptedException {
1778     flush(Bytes.toBytes(tableNameOrRegionName));
1779   }
1780 
1781   /**
1782    * @deprecated Use {@link #flush(org.apache.hadoop.hbase.TableName)} or {@link #flushRegion
1783    * (byte[])} instead.
1784    */
1785   @Deprecated
1786   public void flush(final byte[] tableNameOrRegionName)
1787   throws IOException, InterruptedException {
1788     try {
1789       flushRegion(tableNameOrRegionName);
1790     } catch (IllegalArgumentException e) {
1791       // Unknown region.  Try table.
1792       flush(TableName.valueOf(tableNameOrRegionName));
1793     }
1794   }
1795 
1796   private void flush(final ServerName sn, final HRegionInfo hri)
1797   throws IOException {
1798     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1799     FlushRegionRequest request =
1800       RequestConverter.buildFlushRegionRequest(hri.getRegionName());
1801     try {
1802       admin.flushRegion(null, request);
1803     } catch (ServiceException se) {
1804       throw ProtobufUtil.getRemoteException(se);
1805     }
1806   }
1807 
1808   /**
1809    * {@inheritDoc}
1810    */
1811   @Override
1812   public void compact(final TableName tableName)
1813     throws IOException {
1814     compact(tableName, null, false);
1815   }
1816 
1817   /**
1818    * {@inheritDoc}
1819    */
1820   @Override
1821   public void compactRegion(final byte[] regionName)
1822     throws IOException {
1823     compactRegion(regionName, null, false);
1824   }
1825 
1826   /**
1827    * @deprecated Use {@link #compact(org.apache.hadoop.hbase.TableName)} or {@link #compactRegion
1828    * (byte[])} instead.
1829    */
1830   @Deprecated
1831   public void compact(final String tableNameOrRegionName)
1832   throws IOException {
1833     compact(Bytes.toBytes(tableNameOrRegionName));
1834   }
1835 
1836   /**
1837    * @deprecated Use {@link #compact(org.apache.hadoop.hbase.TableName)} or {@link #compactRegion
1838    * (byte[])} instead.
1839    */
1840   @Deprecated
1841   public void compact(final byte[] tableNameOrRegionName)
1842   throws IOException {
1843     try {
1844       compactRegion(tableNameOrRegionName, null, false);
1845     } catch (IllegalArgumentException e) {
1846       compact(TableName.valueOf(tableNameOrRegionName), null, false);
1847     }
1848   }
1849 
1850   /**
1851    * {@inheritDoc}
1852    */
1853   @Override
1854   public void compact(final TableName tableName, final byte[] columnFamily)
1855     throws IOException {
1856     compact(tableName, columnFamily, false);
1857   }
1858 
1859   /**
1860    * {@inheritDoc}
1861    */
1862   @Override
1863   public void compactRegion(final byte[] regionName, final byte[] columnFamily)
1864     throws IOException {
1865     compactRegion(regionName, columnFamily, false);
1866   }
1867 
1868   /**
1869    * @deprecated Use {@link #compact(org.apache.hadoop.hbase.TableName)} or {@link #compactRegion
1870    * (byte[], byte[])} instead.
1871    */
1872   @Deprecated
1873   public void compact(String tableOrRegionName, String columnFamily)
1874     throws IOException {
1875     compact(Bytes.toBytes(tableOrRegionName), Bytes.toBytes(columnFamily));
1876   }
1877 
1878   /**
1879    * @deprecated Use {@link #compact(org.apache.hadoop.hbase.TableName)} or {@link #compactRegion
1880    * (byte[], byte[])} instead.
1881    */
1882   @Deprecated
1883   public void compact(final byte[] tableNameOrRegionName, final byte[] columnFamily)
1884   throws IOException {
1885     try {
1886       compactRegion(tableNameOrRegionName, columnFamily, false);
1887     } catch (IllegalArgumentException e) {
1888       // Bad region, try table
1889       compact(TableName.valueOf(tableNameOrRegionName), columnFamily, false);
1890     }
1891   }
1892 
1893   /**
1894    * {@inheritDoc}
1895    */
1896   @Override
1897   public void compactRegionServer(final ServerName sn, boolean major)
1898   throws IOException, InterruptedException {
1899     for (HRegionInfo region : getOnlineRegions(sn)) {
1900       compact(sn, region, major, null);
1901     }
1902   }
1903 
1904   /**
1905    * {@inheritDoc}
1906    */
1907   @Override
1908   public void majorCompact(final TableName tableName)
1909   throws IOException {
1910     compact(tableName, null, true);
1911   }
1912 
1913   /**
1914    * {@inheritDoc}
1915    */
1916   @Override
1917   public void majorCompactRegion(final byte[] regionName)
1918   throws IOException {
1919     compactRegion(regionName, null, true);
1920   }
1921 
1922   /**
1923    * @deprecated Use {@link #majorCompact(org.apache.hadoop.hbase.TableName)} or {@link
1924    * #majorCompactRegion(byte[])} instead.
1925    */
1926   @Deprecated
1927   public void majorCompact(final String tableNameOrRegionName)
1928   throws IOException {
1929     majorCompact(Bytes.toBytes(tableNameOrRegionName));
1930   }
1931 
1932   /**
1933    * @deprecated Use {@link #majorCompact(org.apache.hadoop.hbase.TableName)} or {@link
1934    * #majorCompactRegion(byte[])} instead.
1935    */
1936   @Deprecated
1937   public void majorCompact(final byte[] tableNameOrRegionName)
1938   throws IOException {
1939     try {
1940       compactRegion(tableNameOrRegionName, null, true);
1941     } catch (IllegalArgumentException e) {
1942       // Invalid region, try table
1943       compact(TableName.valueOf(tableNameOrRegionName), null, true);
1944     }
1945   }
1946 
1947   /**
1948    * {@inheritDoc}
1949    */
1950   @Override
1951   public void majorCompact(final TableName tableName, final byte[] columnFamily)
1952   throws IOException {
1953     compact(tableName, columnFamily, true);
1954   }
1955 
1956   /**
1957    * {@inheritDoc}
1958    */
1959   @Override
1960   public void majorCompactRegion(final byte[] regionName, final byte[] columnFamily)
1961   throws IOException {
1962     compactRegion(regionName, columnFamily, true);
1963   }
1964 
1965   /**
1966    * @deprecated Use {@link #majorCompact(org.apache.hadoop.hbase.TableName,
1967    * byte[])} or {@link #majorCompactRegion(byte[], byte[])} instead.
1968    */
1969   @Deprecated
1970   public void majorCompact(final String tableNameOrRegionName, final String columnFamily)
1971   throws IOException {
1972     majorCompact(Bytes.toBytes(tableNameOrRegionName), Bytes.toBytes(columnFamily));
1973   }
1974 
1975   /**
1976    * @deprecated Use {@link #majorCompact(org.apache.hadoop.hbase.TableName,
1977    * byte[])} or {@link #majorCompactRegion(byte[], byte[])} instead.
1978    */
1979   @Deprecated
1980   public void majorCompact(final byte[] tableNameOrRegionName, final byte[] columnFamily)
1981   throws IOException {
1982     try {
1983       compactRegion(tableNameOrRegionName, columnFamily, true);
1984     } catch (IllegalArgumentException e) {
1985       // Invalid region, try table
1986       compact(TableName.valueOf(tableNameOrRegionName), columnFamily, true);
1987     }
1988   }
1989 
1990   /**
1991    * Compact a table.
1992    * Asynchronous operation.
1993    *
1994    * @param tableName table or region to compact
1995    * @param columnFamily column family within a table or region
1996    * @param major True if we are to do a major compaction.
1997    * @throws IOException if a remote or network exception occurs
1998    * @throws InterruptedException
1999    */
2000   private void compact(final TableName tableName, final byte[] columnFamily,final boolean major)
2001   throws IOException {
2002     ZooKeeperWatcher zookeeper = null;
2003     try {
2004       checkTableExists(tableName);
2005       zookeeper = new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2006           new ThrowableAbortable());
2007       List<Pair<HRegionInfo, ServerName>> pairs =
2008         MetaTableAccessor.getTableRegionsAndLocations(zookeeper, connection, tableName);
2009       for (Pair<HRegionInfo, ServerName> pair: pairs) {
2010         if (pair.getFirst().isOffline()) continue;
2011         if (pair.getSecond() == null) continue;
2012         try {
2013           compact(pair.getSecond(), pair.getFirst(), major, columnFamily);
2014         } catch (NotServingRegionException e) {
2015           if (LOG.isDebugEnabled()) {
2016             LOG.debug("Trying to" + (major ? " major" : "") + " compact " +
2017               pair.getFirst() + ": " +
2018               StringUtils.stringifyException(e));
2019           }
2020         }
2021       }
2022     } finally {
2023       if (zookeeper != null) {
2024         zookeeper.close();
2025       }
2026     }
2027   }
2028 
2029   /**
2030    * Compact an individual region.
2031    * Asynchronous operation.
2032    *
2033    * @param regionName region to compact
2034    * @param columnFamily column family within a table or region
2035    * @param major True if we are to do a major compaction.
2036    * @throws IOException if a remote or network exception occurs
2037    * @throws InterruptedException
2038    */
2039   private void compactRegion(final byte[] regionName, final byte[] columnFamily,final boolean major)
2040   throws IOException {
2041     Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
2042     if (regionServerPair == null) {
2043       throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName));
2044     }
2045     if (regionServerPair.getSecond() == null) {
2046       throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
2047     }
2048     compact(regionServerPair.getSecond(), regionServerPair.getFirst(), major, columnFamily);
2049   }
2050 
2051   private void compact(final ServerName sn, final HRegionInfo hri,
2052       final boolean major, final byte [] family)
2053   throws IOException {
2054     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2055     CompactRegionRequest request =
2056       RequestConverter.buildCompactRegionRequest(hri.getRegionName(), major, family);
2057     try {
2058       admin.compactRegion(null, request);
2059     } catch (ServiceException se) {
2060       throw ProtobufUtil.getRemoteException(se);
2061     }
2062   }
2063 
2064   /**
2065    * Move the region <code>r</code> to <code>dest</code>.
2066    * @param encodedRegionName The encoded region name; i.e. the hash that makes
2067    * up the region name suffix: e.g. if regionname is
2068    * <code>TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396.</code>,
2069    * then the encoded region name is: <code>527db22f95c8a9e0116f0cc13c680396</code>.
2070    * @param destServerName The servername of the destination regionserver.  If
2071    * passed the empty byte array we'll assign to a random server.  A server name
2072    * is made of host, port and startcode.  Here is an example:
2073    * <code> host187.example.com,60020,1289493121758</code>
2074    * @throws UnknownRegionException Thrown if we can't find a region named
2075    * <code>encodedRegionName</code>
2076    */
2077   @Override
2078   public void move(final byte [] encodedRegionName, final byte [] destServerName)
2079       throws IOException {
2080 
2081     executeCallable(new MasterCallable<Void>(getConnection()) {
2082       @Override
2083       public Void call(int callTimeout) throws ServiceException {
2084         try {
2085           MoveRegionRequest request =
2086               RequestConverter.buildMoveRegionRequest(encodedRegionName, destServerName);
2087             master.moveRegion(null, request);
2088         } catch (DeserializationException de) {
2089           LOG.error("Could not parse destination server name: " + de);
2090           throw new ServiceException(new DoNotRetryIOException(de));
2091         }
2092         return null;
2093       }
2094     });
2095   }
2096 
2097   /**
2098    * @param regionName
2099    *          Region name to assign.
2100    * @throws MasterNotRunningException
2101    * @throws ZooKeeperConnectionException
2102    * @throws IOException
2103    */
2104   @Override
2105   public void assign(final byte[] regionName) throws MasterNotRunningException,
2106       ZooKeeperConnectionException, IOException {
2107     final byte[] toBeAssigned = getRegionName(regionName);
2108     executeCallable(new MasterCallable<Void>(getConnection()) {
2109       @Override
2110       public Void call(int callTimeout) throws ServiceException {
2111         AssignRegionRequest request =
2112           RequestConverter.buildAssignRegionRequest(toBeAssigned);
2113         master.assignRegion(null,request);
2114         return null;
2115       }
2116     });
2117   }
2118 
2119   /**
2120    * Unassign a region from current hosting regionserver.  Region will then be
2121    * assigned to a regionserver chosen at random.  Region could be reassigned
2122    * back to the same server.  Use {@link #move(byte[], byte[])} if you want
2123    * to control the region movement.
2124    * @param regionName Region to unassign. Will clear any existing RegionPlan
2125    * if one found.
2126    * @param force If true, force unassign (Will remove region from
2127    * regions-in-transition too if present. If results in double assignment
2128    * use hbck -fix to resolve. To be used by experts).
2129    * @throws MasterNotRunningException
2130    * @throws ZooKeeperConnectionException
2131    * @throws IOException
2132    */
2133   @Override
2134   public void unassign(final byte [] regionName, final boolean force)
2135   throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
2136     final byte[] toBeUnassigned = getRegionName(regionName);
2137     executeCallable(new MasterCallable<Void>(getConnection()) {
2138       @Override
2139       public Void call(int callTimeout) throws ServiceException {
2140         UnassignRegionRequest request =
2141           RequestConverter.buildUnassignRegionRequest(toBeUnassigned, force);
2142         master.unassignRegion(null, request);
2143         return null;
2144       }
2145     });
2146   }
2147 
2148   /**
2149    * Offline specified region from master's in-memory state. It will not attempt to reassign the
2150    * region as in unassign. This API can be used when a region not served by any region server and
2151    * still online as per Master's in memory state. If this API is incorrectly used on active region
2152    * then master will loose track of that region.
2153    *
2154    * This is a special method that should be used by experts or hbck.
2155    *
2156    * @param regionName
2157    *          Region to offline.
2158    * @throws IOException
2159    */
2160   @Override
2161   public void offline(final byte [] regionName)
2162   throws IOException {
2163     executeCallable(new MasterCallable<Void>(getConnection()) {
2164       @Override
2165       public Void call(int callTimeout) throws ServiceException {
2166         master.offlineRegion(null,RequestConverter.buildOfflineRegionRequest(regionName));
2167         return null;
2168       }
2169     });
2170   }
2171 
2172   /**
2173    * Turn the load balancer on or off.
2174    * @param on If true, enable balancer. If false, disable balancer.
2175    * @param synchronous If true, it waits until current balance() call, if outstanding, to return.
2176    * @return Previous balancer value
2177    */
2178   @Override
2179   public boolean setBalancerRunning(final boolean on, final boolean synchronous)
2180   throws IOException {
2181     return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2182       @Override
2183       public Boolean call(int callTimeout) throws ServiceException {
2184         SetBalancerRunningRequest req =
2185             RequestConverter.buildSetBalancerRunningRequest(on, synchronous);
2186         return master.setBalancerRunning(null, req).getPrevBalanceValue();
2187       }
2188     });
2189   }
2190 
2191   /**
2192    * Invoke the balancer.  Will run the balancer and if regions to move, it will
2193    * go ahead and do the reassignments.  Can NOT run for various reasons.  Check
2194    * logs.
2195    * @return True if balancer ran, false otherwise.
2196    */
2197   @Override
2198   public boolean balancer() throws IOException {
2199     return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2200       @Override
2201       public Boolean call(int callTimeout) throws ServiceException {
2202         return master.balance(null, RequestConverter.buildBalanceRequest()).getBalancerRan();
2203       }
2204     });
2205   }
2206 
2207   /**
2208    * Query the state of the balancer from the Master. It's not a guarantee that the balancer is
2209    * actually running this very moment, but that it will run.
2210    *
2211    * @return True if the balancer is enabled, false otherwise.
2212    */
2213   @Override
2214   public boolean isBalancerEnabled() throws IOException {
2215     return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2216       @Override
2217       public Boolean call(int callTimeout) throws ServiceException {
2218         return master.isBalancerEnabled(null, RequestConverter.buildIsBalancerEnabledRequest())
2219             .getEnabled();
2220       }
2221     });
2222   }
2223 
2224   /**
2225    * Enable/Disable the catalog janitor
2226    * @param enable if true enables the catalog janitor
2227    * @return the previous state
2228    * @throws MasterNotRunningException
2229    */
2230   @Override
2231   public boolean enableCatalogJanitor(final boolean enable)
2232       throws IOException {
2233     return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2234       @Override
2235       public Boolean call(int callTimeout) throws ServiceException {
2236         return master.enableCatalogJanitor(null,
2237           RequestConverter.buildEnableCatalogJanitorRequest(enable)).getPrevValue();
2238       }
2239     });
2240   }
2241 
2242   /**
2243    * Ask for a scan of the catalog table
2244    * @return the number of entries cleaned
2245    * @throws MasterNotRunningException
2246    */
2247   @Override
2248   public int runCatalogScan() throws IOException {
2249     return executeCallable(new MasterCallable<Integer>(getConnection()) {
2250       @Override
2251       public Integer call(int callTimeout) throws ServiceException {
2252         return master.runCatalogScan(null,
2253           RequestConverter.buildCatalogScanRequest()).getScanResult();
2254       }
2255     });
2256   }
2257 
2258   /**
2259    * Query on the catalog janitor state (Enabled/Disabled?)
2260    * @throws org.apache.hadoop.hbase.MasterNotRunningException
2261    */
2262   @Override
2263   public boolean isCatalogJanitorEnabled() throws IOException {
2264     return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2265       @Override
2266       public Boolean call(int callTimeout) throws ServiceException {
2267         return master.isCatalogJanitorEnabled(null,
2268           RequestConverter.buildIsCatalogJanitorEnabledRequest()).getValue();
2269       }
2270     });
2271   }
2272 
2273   /**
2274    * Merge two regions. Asynchronous operation.
2275    * @param encodedNameOfRegionA encoded name of region a
2276    * @param encodedNameOfRegionB encoded name of region b
2277    * @param forcible true if do a compulsory merge, otherwise we will only merge
2278    *          two adjacent regions
2279    * @throws IOException
2280    */
2281   @Override
2282   public void mergeRegions(final byte[] encodedNameOfRegionA,
2283       final byte[] encodedNameOfRegionB, final boolean forcible)
2284       throws IOException {
2285     Pair<HRegionInfo, ServerName> pair = getRegion(encodedNameOfRegionA);
2286     if (pair != null && pair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID)
2287       throw new IllegalArgumentException("Can't invoke merge on non-default regions directly");
2288     pair = getRegion(encodedNameOfRegionB);
2289     if (pair != null && pair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID)
2290       throw new IllegalArgumentException("Can't invoke merge on non-default regions directly");
2291     executeCallable(new MasterCallable<Void>(getConnection()) {
2292       @Override
2293       public Void call(int callTimeout) throws ServiceException {
2294         try {
2295           DispatchMergingRegionsRequest request = RequestConverter
2296               .buildDispatchMergingRegionsRequest(encodedNameOfRegionA,
2297                 encodedNameOfRegionB, forcible);
2298           master.dispatchMergingRegions(null, request);
2299         } catch (DeserializationException de) {
2300           LOG.error("Could not parse destination server name: " + de);
2301         }
2302         return null;
2303       }
2304     });
2305   }
2306 
2307   /**
2308    * {@inheritDoc}
2309    */
2310   @Override
2311   public void split(final TableName tableName)
2312     throws IOException {
2313     split(tableName, null);
2314   }
2315 
2316   /**
2317    * {@inheritDoc}
2318    */
2319   @Override
2320   public void splitRegion(final byte[] regionName)
2321     throws IOException {
2322     splitRegion(regionName, null);
2323   }
2324 
2325   /**
2326    * @deprecated Use {@link #split(org.apache.hadoop.hbase.TableName)} or {@link #splitRegion
2327    * (byte[])} instead.
2328    */
2329   @Deprecated
2330   public void split(final String tableNameOrRegionName)
2331   throws IOException, InterruptedException {
2332     split(Bytes.toBytes(tableNameOrRegionName));
2333   }
2334 
2335   /**
2336    * @deprecated Use {@link #split(org.apache.hadoop.hbase.TableName)} or {@link #splitRegion
2337    * (byte[])} instead.
2338    */
2339   @Deprecated
2340   public void split(final byte[] tableNameOrRegionName)
2341   throws IOException, InterruptedException {
2342     split(tableNameOrRegionName, null);
2343   }
2344 
2345   /**
2346    * {@inheritDoc}
2347    */
2348   @Override
2349   public void split(final TableName tableName, final byte [] splitPoint)
2350   throws IOException {
2351     ZooKeeperWatcher zookeeper = null;
2352     try {
2353       checkTableExists(tableName);
2354       zookeeper = new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2355         new ThrowableAbortable());
2356       List<Pair<HRegionInfo, ServerName>> pairs =
2357         MetaTableAccessor.getTableRegionsAndLocations(zookeeper, connection, tableName);
2358       for (Pair<HRegionInfo, ServerName> pair: pairs) {
2359         // May not be a server for a particular row
2360         if (pair.getSecond() == null) continue;
2361         HRegionInfo r = pair.getFirst();
2362         // check for parents
2363         if (r.isSplitParent()) continue;
2364         // if a split point given, only split that particular region
2365         if (r.getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID ||
2366            (splitPoint != null && !r.containsRow(splitPoint))) continue;
2367         // call out to region server to do split now
2368         split(pair.getSecond(), pair.getFirst(), splitPoint);
2369       }
2370     } finally {
2371       if (zookeeper != null) {
2372         zookeeper.close();
2373       }
2374     }
2375   }
2376 
2377   /**
2378    * {@inheritDoc}
2379    */
2380   @Override
2381   public void splitRegion(final byte[] regionName, final byte [] splitPoint)
2382   throws IOException {
2383     Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
2384     if (regionServerPair == null) {
2385       throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName));
2386     }
2387     if (regionServerPair.getFirst() != null &&
2388         regionServerPair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID) {
2389       throw new IllegalArgumentException("Can't split replicas directly. "
2390           + "Replicas are auto-split when their primary is split.");
2391     }
2392     if (regionServerPair.getSecond() == null) {
2393       throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
2394     }
2395     split(regionServerPair.getSecond(), regionServerPair.getFirst(), splitPoint);
2396   }
2397 
2398   /**
2399    * @deprecated Use {@link #split(org.apache.hadoop.hbase.TableName,
2400    * byte[])} or {@link #splitRegion(byte[], byte[])} instead.
2401    */
2402   @Deprecated
2403   public void split(final String tableNameOrRegionName,
2404     final String splitPoint) throws IOException {
2405     split(Bytes.toBytes(tableNameOrRegionName), Bytes.toBytes(splitPoint));
2406   }
2407 
2408   /**
2409    * @deprecated Use {@link #split(org.apache.hadoop.hbase.TableName,
2410    * byte[])} or {@link #splitRegion(byte[], byte[])} instead.
2411    */
2412   @Deprecated
2413   public void split(final byte[] tableNameOrRegionName,
2414       final byte [] splitPoint) throws IOException {
2415     try {
2416       splitRegion(tableNameOrRegionName, splitPoint);
2417     } catch (IllegalArgumentException e) {
2418       // Bad region, try table
2419       split(TableName.valueOf(tableNameOrRegionName), splitPoint);
2420     }
2421   }
2422 
2423   @VisibleForTesting
2424   public void split(final ServerName sn, final HRegionInfo hri,
2425       byte[] splitPoint) throws IOException {
2426     if (hri.getStartKey() != null && splitPoint != null &&
2427          Bytes.compareTo(hri.getStartKey(), splitPoint) == 0) {
2428        throw new IOException("should not give a splitkey which equals to startkey!");
2429     }
2430     // TODO: This is not executed via retries
2431     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2432     ProtobufUtil.split(admin, hri, splitPoint);
2433   }
2434 
2435   /**
2436    * Modify an existing table, more IRB friendly version.
2437    * Asynchronous operation.  This means that it may be a while before your
2438    * schema change is updated across all of the table.
2439    *
2440    * @param tableName name of table.
2441    * @param htd modified description of the table
2442    * @throws IOException if a remote or network exception occurs
2443    */
2444   @Override
2445   public void modifyTable(final TableName tableName, final HTableDescriptor htd)
2446   throws IOException {
2447     if (!tableName.equals(htd.getTableName())) {
2448       throw new IllegalArgumentException("the specified table name '" + tableName +
2449         "' doesn't match with the HTD one: " + htd.getTableName());
2450     }
2451 
2452     executeCallable(new MasterCallable<Void>(getConnection()) {
2453       @Override
2454       public Void call(int callTimeout) throws ServiceException {
2455         ModifyTableRequest request = RequestConverter.buildModifyTableRequest(tableName, htd);
2456         master.modifyTable(null, request);
2457         return null;
2458       }
2459     });
2460   }
2461 
2462   public void modifyTable(final byte[] tableName, final HTableDescriptor htd)
2463   throws IOException {
2464     modifyTable(TableName.valueOf(tableName), htd);
2465   }
2466 
2467   public void modifyTable(final String tableName, final HTableDescriptor htd)
2468   throws IOException {
2469     modifyTable(TableName.valueOf(tableName), htd);
2470   }
2471 
2472   /**
2473    * @param regionName Name of a region.
2474    * @return a pair of HRegionInfo and ServerName if <code>regionName</code> is
2475    *  a verified region name (we call {@link
2476    *  MetaTableAccessor#getRegion(HConnection, byte[])}
2477    *  else null.
2478    * Throw IllegalArgumentException if <code>regionName</code> is null.
2479    * @throws IOException
2480    */
2481   Pair<HRegionInfo, ServerName> getRegion(final byte[] regionName) throws IOException {
2482     if (regionName == null) {
2483       throw new IllegalArgumentException("Pass a table name or region name");
2484     }
2485     Pair<HRegionInfo, ServerName> pair =
2486       MetaTableAccessor.getRegion(connection, regionName);
2487     if (pair == null) {
2488       final AtomicReference<Pair<HRegionInfo, ServerName>> result =
2489         new AtomicReference<Pair<HRegionInfo, ServerName>>(null);
2490       final String encodedName = Bytes.toString(regionName);
2491       MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
2492         @Override
2493         public boolean processRow(Result data) throws IOException {
2494           HRegionInfo info = HRegionInfo.getHRegionInfo(data);
2495           if (info == null) {
2496             LOG.warn("No serialized HRegionInfo in " + data);
2497             return true;
2498           }
2499           RegionLocations rl = MetaTableAccessor.getRegionLocations(data);
2500           boolean matched = false;
2501           ServerName sn = null;
2502           for (HRegionLocation h : rl.getRegionLocations()) {
2503             if (h != null && encodedName.equals(h.getRegionInfo().getEncodedName())) {
2504               sn = h.getServerName();
2505               info = h.getRegionInfo();
2506               matched = true;
2507             }
2508           }
2509           if (!matched) return true;
2510           result.set(new Pair<HRegionInfo, ServerName>(info, sn));
2511           return false; // found the region, stop
2512         }
2513       };
2514 
2515       MetaScanner.metaScan(connection, visitor, null);
2516       pair = result.get();
2517     }
2518     return pair;
2519   }
2520 
2521   /**
2522    * If the input is a region name, it is returned as is. If it's an
2523    * encoded region name, the corresponding region is found from meta
2524    * and its region name is returned. If we can't find any region in
2525    * meta matching the input as either region name or encoded region
2526    * name, the input is returned as is. We don't throw unknown
2527    * region exception.
2528    */
2529   private byte[] getRegionName(
2530       final byte[] regionNameOrEncodedRegionName) throws IOException {
2531     if (Bytes.equals(regionNameOrEncodedRegionName,
2532         HRegionInfo.FIRST_META_REGIONINFO.getRegionName())
2533           || Bytes.equals(regionNameOrEncodedRegionName,
2534             HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) {
2535       return HRegionInfo.FIRST_META_REGIONINFO.getRegionName();
2536     }
2537     byte[] tmp = regionNameOrEncodedRegionName;
2538     Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionNameOrEncodedRegionName);
2539     if (regionServerPair != null && regionServerPair.getFirst() != null) {
2540       tmp = regionServerPair.getFirst().getRegionName();
2541     }
2542     return tmp;
2543   }
2544 
2545   /**
2546    * Check if table exists or not
2547    * @param tableName Name of a table.
2548    * @return tableName instance
2549    * @throws IOException if a remote or network exception occurs.
2550    * @throws TableNotFoundException if table does not exist.
2551    */
2552   private TableName checkTableExists(final TableName tableName)
2553       throws IOException {
2554     if (!MetaTableAccessor.tableExists(connection, tableName)) {
2555       throw new TableNotFoundException(tableName);
2556     }
2557     return tableName;
2558   }
2559 
2560   /**
2561    * Shuts down the HBase cluster
2562    * @throws IOException if a remote or network exception occurs
2563    */
2564   @Override
2565   public synchronized void shutdown() throws IOException {
2566     executeCallable(new MasterCallable<Void>(getConnection()) {
2567       @Override
2568       public Void call(int callTimeout) throws ServiceException {
2569         master.shutdown(null,ShutdownRequest.newBuilder().build());
2570         return null;
2571       }
2572     });
2573   }
2574 
2575   /**
2576    * Shuts down the current HBase master only.
2577    * Does not shutdown the cluster.
2578    * @see #shutdown()
2579    * @throws IOException if a remote or network exception occurs
2580    */
2581   @Override
2582   public synchronized void stopMaster() throws IOException {
2583     executeCallable(new MasterCallable<Void>(getConnection()) {
2584       @Override
2585       public Void call(int callTimeout) throws ServiceException {
2586         master.stopMaster(null, StopMasterRequest.newBuilder().build());
2587         return null;
2588       }
2589     });
2590   }
2591 
2592   /**
2593    * Stop the designated regionserver
2594    * @param hostnamePort Hostname and port delimited by a <code>:</code> as in
2595    * <code>example.org:1234</code>
2596    * @throws IOException if a remote or network exception occurs
2597    */
2598   @Override
2599   public synchronized void stopRegionServer(final String hostnamePort)
2600   throws IOException {
2601     String hostname = Addressing.parseHostname(hostnamePort);
2602     int port = Addressing.parsePort(hostnamePort);
2603     AdminService.BlockingInterface admin =
2604       this.connection.getAdmin(ServerName.valueOf(hostname, port, 0));
2605     StopServerRequest request = RequestConverter.buildStopServerRequest(
2606       "Called by admin client " + this.connection.toString());
2607     try {
2608       admin.stopServer(null, request);
2609     } catch (ServiceException se) {
2610       throw ProtobufUtil.getRemoteException(se);
2611     }
2612   }
2613 
2614 
2615   /**
2616    * @return cluster status
2617    * @throws IOException if a remote or network exception occurs
2618    */
2619   @Override
2620   public ClusterStatus getClusterStatus() throws IOException {
2621     return executeCallable(new MasterCallable<ClusterStatus>(getConnection()) {
2622       @Override
2623       public ClusterStatus call(int callTimeout) throws ServiceException {
2624         GetClusterStatusRequest req = RequestConverter.buildGetClusterStatusRequest();
2625         return ClusterStatus.convert(master.getClusterStatus(null, req).getClusterStatus());
2626       }
2627     });
2628   }
2629 
2630   /**
2631    * @return Configuration used by the instance.
2632    */
2633   @Override
2634   public Configuration getConfiguration() {
2635     return this.conf;
2636   }
2637 
2638   /**
2639    * Create a new namespace
2640    * @param descriptor descriptor which describes the new namespace
2641    * @throws IOException
2642    */
2643   @Override
2644   public void createNamespace(final NamespaceDescriptor descriptor) throws IOException {
2645     executeCallable(new MasterCallable<Void>(getConnection()) {
2646       @Override
2647       public Void call(int callTimeout) throws Exception {
2648         master.createNamespace(null,
2649           CreateNamespaceRequest.newBuilder()
2650             .setNamespaceDescriptor(ProtobufUtil
2651               .toProtoNamespaceDescriptor(descriptor)).build()
2652         );
2653         return null;
2654       }
2655     });
2656   }
2657 
2658   /**
2659    * Modify an existing namespace
2660    * @param descriptor descriptor which describes the new namespace
2661    * @throws IOException
2662    */
2663   @Override
2664   public void modifyNamespace(final NamespaceDescriptor descriptor) throws IOException {
2665     executeCallable(new MasterCallable<Void>(getConnection()) {
2666       @Override
2667       public Void call(int callTimeout) throws Exception {
2668         master.modifyNamespace(null, ModifyNamespaceRequest.newBuilder().
2669           setNamespaceDescriptor(ProtobufUtil.toProtoNamespaceDescriptor(descriptor)).build());
2670         return null;
2671       }
2672     });
2673   }
2674 
2675   /**
2676    * Delete an existing namespace. Only empty namespaces (no tables) can be removed.
2677    * @param name namespace name
2678    * @throws IOException
2679    */
2680   @Override
2681   public void deleteNamespace(final String name) throws IOException {
2682     executeCallable(new MasterCallable<Void>(getConnection()) {
2683       @Override
2684       public Void call(int callTimeout) throws Exception {
2685         master.deleteNamespace(null, DeleteNamespaceRequest.newBuilder().
2686           setNamespaceName(name).build());
2687         return null;
2688       }
2689     });
2690   }
2691 
2692   /**
2693    * Get a namespace descriptor by name
2694    * @param name name of namespace descriptor
2695    * @return A descriptor
2696    * @throws IOException
2697    */
2698   @Override
2699   public NamespaceDescriptor getNamespaceDescriptor(final String name) throws IOException {
2700     return
2701         executeCallable(new MasterCallable<NamespaceDescriptor>(getConnection()) {
2702           @Override
2703           public NamespaceDescriptor call(int callTimeout) throws Exception {
2704             return ProtobufUtil.toNamespaceDescriptor(
2705               master.getNamespaceDescriptor(null, GetNamespaceDescriptorRequest.newBuilder().
2706                 setNamespaceName(name).build()).getNamespaceDescriptor());
2707           }
2708         });
2709   }
2710 
2711   /**
2712    * List available namespace descriptors
2713    * @return List of descriptors
2714    * @throws IOException
2715    */
2716   @Override
2717   public NamespaceDescriptor[] listNamespaceDescriptors() throws IOException {
2718     return
2719         executeCallable(new MasterCallable<NamespaceDescriptor[]>(getConnection()) {
2720           @Override
2721           public NamespaceDescriptor[] call(int callTimeout) throws Exception {
2722             List<HBaseProtos.NamespaceDescriptor> list =
2723               master.listNamespaceDescriptors(null, ListNamespaceDescriptorsRequest.newBuilder().
2724                 build()).getNamespaceDescriptorList();
2725             NamespaceDescriptor[] res = new NamespaceDescriptor[list.size()];
2726             for(int i = 0; i < list.size(); i++) {
2727               res[i] = ProtobufUtil.toNamespaceDescriptor(list.get(i));
2728             }
2729             return res;
2730           }
2731         });
2732   }
2733 
2734   /**
2735    * Get list of table descriptors by namespace
2736    * @param name namespace name
2737    * @return A descriptor
2738    * @throws IOException
2739    */
2740   @Override
2741   public HTableDescriptor[] listTableDescriptorsByNamespace(final String name) throws IOException {
2742     return
2743         executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
2744           @Override
2745           public HTableDescriptor[] call(int callTimeout) throws Exception {
2746             List<TableSchema> list =
2747               master.listTableDescriptorsByNamespace(null, ListTableDescriptorsByNamespaceRequest.
2748                 newBuilder().setNamespaceName(name).build()).getTableSchemaList();
2749             HTableDescriptor[] res = new HTableDescriptor[list.size()];
2750             for(int i=0; i < list.size(); i++) {
2751 
2752               res[i] = HTableDescriptor.convert(list.get(i));
2753             }
2754             return res;
2755           }
2756         });
2757   }
2758 
2759   /**
2760    * Get list of table names by namespace
2761    * @param name namespace name
2762    * @return The list of table names in the namespace
2763    * @throws IOException
2764    */
2765   @Override
2766   public TableName[] listTableNamesByNamespace(final String name) throws IOException {
2767     return
2768         executeCallable(new MasterCallable<TableName[]>(getConnection()) {
2769           @Override
2770           public TableName[] call(int callTimeout) throws Exception {
2771             List<HBaseProtos.TableName> tableNames =
2772               master.listTableNamesByNamespace(null, ListTableNamesByNamespaceRequest.
2773                 newBuilder().setNamespaceName(name).build())
2774                 .getTableNameList();
2775             TableName[] result = new TableName[tableNames.size()];
2776             for (int i = 0; i < tableNames.size(); i++) {
2777               result[i] = ProtobufUtil.toTableName(tableNames.get(i));
2778             }
2779             return result;
2780           }
2781         });
2782   }
2783 
2784   /**
2785    * Check to see if HBase is running. Throw an exception if not.
2786    * @param conf system configuration
2787    * @throws MasterNotRunningException if the master is not running
2788    * @throws ZooKeeperConnectionException if unable to connect to zookeeper
2789    */
2790   // Used by tests and by the Merge tool. Merge tool uses it to figure if HBase is up or not.
2791   public static void checkHBaseAvailable(Configuration conf)
2792   throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException, IOException {
2793     Configuration copyOfConf = HBaseConfiguration.create(conf);
2794     // We set it to make it fail as soon as possible if HBase is not available
2795     copyOfConf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
2796     copyOfConf.setInt("zookeeper.recovery.retry", 0);
2797     try (ClusterConnection connection =
2798         (ClusterConnection)ConnectionFactory.createConnection(copyOfConf)) {
2799         // Check ZK first.
2800         // If the connection exists, we may have a connection to ZK that does not work anymore
2801         ZooKeeperKeepAliveConnection zkw = null;
2802         try {
2803           // This is NASTY. FIX!!!! Dependent on internal implementation! TODO
2804           zkw = ((ConnectionManager.HConnectionImplementation)connection).
2805             getKeepAliveZooKeeperWatcher();
2806           zkw.getRecoverableZooKeeper().getZooKeeper().exists(zkw.baseZNode, false);
2807         } catch (IOException e) {
2808           throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
2809         } catch (InterruptedException e) {
2810           throw (InterruptedIOException)
2811             new InterruptedIOException("Can't connect to ZooKeeper").initCause(e);
2812         } catch (KeeperException e) {
2813           throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
2814         } finally {
2815           if (zkw != null) {
2816             zkw.close();
2817           }
2818         }
2819       connection.isMasterRunning();
2820     }
2821   }
2822 
2823   /**
2824    * get the regions of a given table.
2825    *
2826    * @param tableName the name of the table
2827    * @return Ordered list of {@link HRegionInfo}.
2828    * @throws IOException
2829    */
2830   @Override
2831   public List<HRegionInfo> getTableRegions(final TableName tableName)
2832   throws IOException {
2833     ZooKeeperWatcher zookeeper =
2834       new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2835         new ThrowableAbortable());
2836     List<HRegionInfo> Regions = null;
2837     try {
2838       Regions = MetaTableAccessor.getTableRegions(zookeeper, connection, tableName, true);
2839     } finally {
2840       zookeeper.close();
2841     }
2842     return Regions;
2843   }
2844 
2845   public List<HRegionInfo> getTableRegions(final byte[] tableName)
2846   throws IOException {
2847     return getTableRegions(TableName.valueOf(tableName));
2848   }
2849 
2850   @Override
2851   public synchronized void close() throws IOException {
2852     if (cleanupConnectionOnClose && this.connection != null && !this.closed) {
2853       this.connection.close();
2854       this.closed = true;
2855     }
2856   }
2857 
2858   /**
2859    * Get tableDescriptors
2860    * @param tableNames List of table names
2861    * @return HTD[] the tableDescriptor
2862    * @throws IOException if a remote or network exception occurs
2863    */
2864   @Override
2865   public HTableDescriptor[] getTableDescriptorsByTableName(final List<TableName> tableNames)
2866   throws IOException {
2867     return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
2868       @Override
2869       public HTableDescriptor[] call(int callTimeout) throws Exception {
2870         GetTableDescriptorsRequest req =
2871             RequestConverter.buildGetTableDescriptorsRequest(tableNames);
2872           return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
2873       }
2874     });
2875   }
2876 
2877   /**
2878    * Get tableDescriptor
2879    * @param tableName one table name
2880    * @return HTD the HTableDescriptor or null if the table not exists
2881    * @throws IOException if a remote or network exception occurs
2882    */
2883   private HTableDescriptor getTableDescriptorByTableName(TableName tableName)
2884       throws IOException {
2885     List<TableName> tableNames = new ArrayList<TableName>(1);
2886     tableNames.add(tableName);
2887 
2888     HTableDescriptor[] htdl = getTableDescriptorsByTableName(tableNames);
2889 
2890     if (htdl == null || htdl.length == 0) {
2891       return null;
2892     }
2893     else {
2894       return htdl[0];
2895     }
2896   }
2897 
2898   /**
2899    * Get tableDescriptors
2900    * @param names List of table names
2901    * @return HTD[] the tableDescriptor
2902    * @throws IOException if a remote or network exception occurs
2903    */
2904   @Override
2905   public HTableDescriptor[] getTableDescriptors(List<String> names)
2906   throws IOException {
2907     List<TableName> tableNames = new ArrayList<TableName>(names.size());
2908     for(String name : names) {
2909       tableNames.add(TableName.valueOf(name));
2910     }
2911     return getTableDescriptorsByTableName(tableNames);
2912   }
2913 
2914   private RollWALWriterResponse rollWALWriterImpl(final ServerName sn) throws IOException,
2915       FailedLogCloseException {
2916     AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2917     RollWALWriterRequest request = RequestConverter.buildRollWALWriterRequest();
2918     try {
2919       return admin.rollWALWriter(null, request);
2920     } catch (ServiceException se) {
2921       throw ProtobufUtil.getRemoteException(se);
2922     }
2923   }
2924 
2925   /**
2926    * Roll the log writer. I.e. when using a file system based write ahead log,
2927    * start writing log messages to a new file.
2928    *
2929    * Note that when talking to a version 1.0+ HBase deployment, the rolling is asynchronous.
2930    * This method will return as soon as the roll is requested and the return value will
2931    * always be null. Additionally, the named region server may schedule store flushes at the
2932    * request of the wal handling the roll request.
2933    *
2934    * When talking to a 0.98 or older HBase deployment, the rolling is synchronous and the
2935    * return value may be either null or a list of encoded region names.
2936    *
2937    * @param serverName
2938    *          The servername of the regionserver. A server name is made of host,
2939    *          port and startcode. This is mandatory. Here is an example:
2940    *          <code> host187.example.com,60020,1289493121758</code>
2941    * @return a set of {@link HRegionInfo#getEncodedName()} that would allow the wal to
2942    *         clean up some underlying files. null if there's nothing to flush.
2943    * @throws IOException if a remote or network exception occurs
2944    * @throws FailedLogCloseException
2945    * @deprecated use {@link #rollWALWriter(ServerName)}
2946    */
2947   @Deprecated
2948   public synchronized byte[][] rollHLogWriter(String serverName)
2949       throws IOException, FailedLogCloseException {
2950     ServerName sn = ServerName.valueOf(serverName);
2951     final RollWALWriterResponse response = rollWALWriterImpl(sn);
2952     int regionCount = response.getRegionToFlushCount();
2953     if (0 == regionCount) {
2954       return null;
2955     }
2956     byte[][] regionsToFlush = new byte[regionCount][];
2957     for (int i = 0; i < regionCount; i++) {
2958       ByteString region = response.getRegionToFlush(i);
2959       regionsToFlush[i] = region.toByteArray();
2960     }
2961     return regionsToFlush;
2962   }
2963 
2964   @Override
2965   public synchronized void rollWALWriter(ServerName serverName)
2966       throws IOException, FailedLogCloseException {
2967     rollWALWriterImpl(serverName);
2968   }
2969 
2970   @Override
2971   public String[] getMasterCoprocessors() {
2972     try {
2973       return getClusterStatus().getMasterCoprocessors();
2974     } catch (IOException e) {
2975       LOG.error("Could not getClusterStatus()",e);
2976       return null;
2977     }
2978   }
2979 
2980   /**
2981    * {@inheritDoc}
2982    */
2983   @Override
2984   public CompactionState getCompactionState(final TableName tableName)
2985   throws IOException {
2986     CompactionState state = CompactionState.NONE;
2987     ZooKeeperWatcher zookeeper =
2988       new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2989         new ThrowableAbortable());
2990     try {
2991       checkTableExists(tableName);
2992       List<Pair<HRegionInfo, ServerName>> pairs =
2993         MetaTableAccessor.getTableRegionsAndLocations(zookeeper, connection, tableName);
2994       for (Pair<HRegionInfo, ServerName> pair: pairs) {
2995         if (pair.getFirst().isOffline()) continue;
2996         if (pair.getSecond() == null) continue;
2997         try {
2998           ServerName sn = pair.getSecond();
2999           AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
3000           GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
3001             pair.getFirst().getRegionName(), true);
3002           GetRegionInfoResponse response = admin.getRegionInfo(null, request);
3003           switch (response.getCompactionState()) {
3004           case MAJOR_AND_MINOR:
3005             return CompactionState.MAJOR_AND_MINOR;
3006           case MAJOR:
3007             if (state == CompactionState.MINOR) {
3008               return CompactionState.MAJOR_AND_MINOR;
3009             }
3010             state = CompactionState.MAJOR;
3011             break;
3012           case MINOR:
3013             if (state == CompactionState.MAJOR) {
3014               return CompactionState.MAJOR_AND_MINOR;
3015             }
3016             state = CompactionState.MINOR;
3017             break;
3018           case NONE:
3019           default: // nothing, continue
3020           }
3021         } catch (NotServingRegionException e) {
3022           if (LOG.isDebugEnabled()) {
3023             LOG.debug("Trying to get compaction state of " +
3024               pair.getFirst() + ": " +
3025               StringUtils.stringifyException(e));
3026           }
3027         } catch (RemoteException e) {
3028           if (e.getMessage().indexOf(NotServingRegionException.class.getName()) >= 0) {
3029             if (LOG.isDebugEnabled()) {
3030               LOG.debug("Trying to get compaction state of " + pair.getFirst() + ": "
3031                 + StringUtils.stringifyException(e));
3032             }
3033           } else {
3034             throw e;
3035           }
3036         }
3037       }
3038     } catch (ServiceException se) {
3039       throw ProtobufUtil.getRemoteException(se);
3040     } finally {
3041       zookeeper.close();
3042     }
3043     return state;
3044   }
3045 
3046   /**
3047    * {@inheritDoc}
3048    */
3049   @Override
3050   public CompactionState getCompactionStateForRegion(final byte[] regionName)
3051   throws IOException {
3052     try {
3053       Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
3054       if (regionServerPair == null) {
3055         throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName));
3056       }
3057       if (regionServerPair.getSecond() == null) {
3058         throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
3059       }
3060       ServerName sn = regionServerPair.getSecond();
3061       AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
3062       GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
3063         regionServerPair.getFirst().getRegionName(), true);
3064       GetRegionInfoResponse response = admin.getRegionInfo(null, request);
3065       return response.getCompactionState();
3066     } catch (ServiceException se) {
3067       throw ProtobufUtil.getRemoteException(se);
3068     }
3069   }
3070 
3071   /**
3072    * @deprecated Use {@link #getCompactionState(org.apache.hadoop.hbase.TableName)} or {@link
3073    * #getCompactionStateForRegion(byte[])} instead.
3074    */
3075   @Deprecated
3076   public CompactionState getCompactionState(final String tableNameOrRegionName)
3077   throws IOException, InterruptedException {
3078     return getCompactionState(Bytes.toBytes(tableNameOrRegionName));
3079   }
3080 
3081   /**
3082    * @deprecated Use {@link #getCompactionState(org.apache.hadoop.hbase.TableName)} or {@link
3083    * #getCompactionStateForRegion(byte[])} instead.
3084    */
3085   @Deprecated
3086   public CompactionState getCompactionState(final byte[] tableNameOrRegionName)
3087   throws IOException, InterruptedException {
3088     try {
3089       return getCompactionStateForRegion(tableNameOrRegionName);
3090     } catch (IllegalArgumentException e) {
3091       // Invalid region, try table
3092       return getCompactionState(TableName.valueOf(tableNameOrRegionName));
3093     }
3094   }
3095 
3096   /**
3097    * Take a snapshot for the given table. If the table is enabled, a FLUSH-type snapshot will be
3098    * taken. If the table is disabled, an offline snapshot is taken.
3099    * <p>
3100    * Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
3101    * snapshot with the same name (even a different type or with different parameters) will fail with
3102    * a {@link SnapshotCreationException} indicating the duplicate naming.
3103    * <p>
3104    * Snapshot names follow the same naming constraints as tables in HBase. See
3105    * {@link org.apache.hadoop.hbase.TableName#isLegalFullyQualifiedTableName(byte[])}.
3106    * @param snapshotName name of the snapshot to be created
3107    * @param tableName name of the table for which snapshot is created
3108    * @throws IOException if a remote or network exception occurs
3109    * @throws SnapshotCreationException if snapshot creation failed
3110    * @throws IllegalArgumentException if the snapshot request is formatted incorrectly
3111    */
3112   @Override
3113   public void snapshot(final String snapshotName,
3114                        final TableName tableName) throws IOException,
3115       SnapshotCreationException, IllegalArgumentException {
3116     snapshot(snapshotName, tableName, SnapshotDescription.Type.FLUSH);
3117   }
3118 
3119   public void snapshot(final String snapshotName,
3120                        final String tableName) throws IOException,
3121       SnapshotCreationException, IllegalArgumentException {
3122     snapshot(snapshotName, TableName.valueOf(tableName),
3123         SnapshotDescription.Type.FLUSH);
3124   }
3125 
3126   /**
3127    * Create snapshot for the given table of given flush type.
3128    * <p>
3129    * Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
3130    * snapshot with the same name (even a different type or with different parameters) will fail with
3131    * a {@link SnapshotCreationException} indicating the duplicate naming.
3132    * <p>
3133    * Snapshot names follow the same naming constraints as tables in HBase.
3134    * @param snapshotName name of the snapshot to be created
3135    * @param tableName name of the table for which snapshot is created
3136    * @param flushType if the snapshot should be taken without flush memstore first
3137    * @throws IOException if a remote or network exception occurs
3138    * @throws SnapshotCreationException if snapshot creation failed
3139    * @throws IllegalArgumentException if the snapshot request is formatted incorrectly
3140    */
3141    public void snapshot(final byte[] snapshotName, final byte[] tableName,
3142                        final SnapshotDescription.Type flushType) throws
3143       IOException, SnapshotCreationException, IllegalArgumentException {
3144       snapshot(Bytes.toString(snapshotName), Bytes.toString(tableName), flushType);
3145   }
3146   /**
3147    public void snapshot(final String snapshotName,
3148     * Create a timestamp consistent snapshot for the given table.
3149                         final byte[] tableName) throws IOException,
3150     * <p>
3151     * Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
3152     * snapshot with the same name (even a different type or with different parameters) will fail with
3153     * a {@link SnapshotCreationException} indicating the duplicate naming.
3154     * <p>
3155     * Snapshot names follow the same naming constraints as tables in HBase.
3156     * @param snapshotName name of the snapshot to be created
3157     * @param tableName name of the table for which snapshot is created
3158     * @throws IOException if a remote or network exception occurs
3159     * @throws SnapshotCreationException if snapshot creation failed
3160     * @throws IllegalArgumentException if the snapshot request is formatted incorrectly
3161     */
3162   @Override
3163   public void snapshot(final byte[] snapshotName,
3164                        final TableName tableName) throws IOException,
3165       SnapshotCreationException, IllegalArgumentException {
3166     snapshot(Bytes.toString(snapshotName), tableName, SnapshotDescription.Type.FLUSH);
3167   }
3168 
3169   public void snapshot(final byte[] snapshotName,
3170                        final byte[] tableName) throws IOException,
3171       SnapshotCreationException, IllegalArgumentException {
3172     snapshot(Bytes.toString(snapshotName), TableName.valueOf(tableName),
3173       SnapshotDescription.Type.FLUSH);
3174   }
3175 
3176   /**
3177    * Create typed snapshot of the table.
3178    * <p>
3179    * Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
3180    * snapshot with the same name (even a different type or with different parameters) will fail with
3181    * a {@link SnapshotCreationException} indicating the duplicate naming.
3182    * <p>
3183    * Snapshot names follow the same naming constraints as tables in HBase. See
3184    * {@link org.apache.hadoop.hbase.TableName#isLegalFullyQualifiedTableName(byte[])}.
3185    * <p>
3186    * @param snapshotName name to give the snapshot on the filesystem. Must be unique from all other
3187    *          snapshots stored on the cluster
3188    * @param tableName name of the table to snapshot
3189    * @param type type of snapshot to take
3190    * @throws IOException we fail to reach the master
3191    * @throws SnapshotCreationException if snapshot creation failed
3192    * @throws IllegalArgumentException if the snapshot request is formatted incorrectly
3193    */
3194   @Override
3195   public void snapshot(final String snapshotName,
3196                        final TableName tableName,
3197                       SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
3198       IllegalArgumentException {
3199     SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
3200     builder.setTable(tableName.getNameAsString());
3201     builder.setName(snapshotName);
3202     builder.setType(type);
3203     snapshot(builder.build());
3204   }
3205 
3206   public void snapshot(final String snapshotName,
3207                        final String tableName,
3208                       SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
3209       IllegalArgumentException {
3210     snapshot(snapshotName, TableName.valueOf(tableName), type);
3211   }
3212 
3213   public void snapshot(final String snapshotName,
3214                        final byte[] tableName,
3215                       SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
3216       IllegalArgumentException {
3217     snapshot(snapshotName, TableName.valueOf(tableName), type);
3218   }
3219 
3220   /**
3221    * Take a snapshot and wait for the server to complete that snapshot (blocking).
3222    * <p>
3223    * Only a single snapshot should be taken at a time for an instance of HBase, or results may be
3224    * undefined (you can tell multiple HBase clusters to snapshot at the same time, but only one at a
3225    * time for a single cluster).
3226    * <p>
3227    * Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
3228    * snapshot with the same name (even a different type or with different parameters) will fail with
3229    * a {@link SnapshotCreationException} indicating the duplicate naming.
3230    * <p>
3231    * Snapshot names follow the same naming constraints as tables in HBase. See
3232    * {@link org.apache.hadoop.hbase.TableName#isLegalFullyQualifiedTableName(byte[])}.
3233    * <p>
3234    * You should probably use {@link #snapshot(String, String)} or {@link #snapshot(byte[], byte[])}
3235    * unless you are sure about the type of snapshot that you want to take.
3236    * @param snapshot snapshot to take
3237    * @throws IOException or we lose contact with the master.
3238    * @throws SnapshotCreationException if snapshot failed to be taken
3239    * @throws IllegalArgumentException if the snapshot request is formatted incorrectly
3240    */
3241   @Override
3242   public void snapshot(SnapshotDescription snapshot) throws IOException, SnapshotCreationException,
3243       IllegalArgumentException {
3244     // actually take the snapshot
3245     SnapshotResponse response = takeSnapshotAsync(snapshot);
3246     final IsSnapshotDoneRequest request = IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot)
3247         .build();
3248     IsSnapshotDoneResponse done = null;
3249     long start = EnvironmentEdgeManager.currentTime();
3250     long max = response.getExpectedTimeout();
3251     long maxPauseTime = max / this.numRetries;
3252     int tries = 0;
3253     LOG.debug("Waiting a max of " + max + " ms for snapshot '" +
3254         ClientSnapshotDescriptionUtils.toString(snapshot) + "'' to complete. (max " +
3255         maxPauseTime + " ms per retry)");
3256     while (tries == 0
3257         || ((EnvironmentEdgeManager.currentTime() - start) < max && !done.getDone())) {
3258       try {
3259         // sleep a backoff <= pauseTime amount
3260         long sleep = getPauseTime(tries++);
3261         sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3262         LOG.debug("(#" + tries + ") Sleeping: " + sleep +
3263           "ms while waiting for snapshot completion.");
3264         Thread.sleep(sleep);
3265       } catch (InterruptedException e) {
3266         throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
3267       }
3268       LOG.debug("Getting current status of snapshot from master...");
3269       done = executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection()) {
3270         @Override
3271         public IsSnapshotDoneResponse call(int callTimeout) throws ServiceException {
3272           return master.isSnapshotDone(null, request);
3273         }
3274       });
3275     }
3276     if (!done.getDone()) {
3277       throw new SnapshotCreationException("Snapshot '" + snapshot.getName()
3278           + "' wasn't completed in expectedTime:" + max + " ms", snapshot);
3279     }
3280   }
3281 
3282   /**
3283    * Take a snapshot without waiting for the server to complete that snapshot (asynchronous)
3284    * <p>
3285    * Only a single snapshot should be taken at a time, or results may be undefined.
3286    * @param snapshot snapshot to take
3287    * @return response from the server indicating the max time to wait for the snapshot
3288    * @throws IOException if the snapshot did not succeed or we lose contact with the master.
3289    * @throws SnapshotCreationException if snapshot creation failed
3290    * @throws IllegalArgumentException if the snapshot request is formatted incorrectly
3291    */
3292   @Override
3293   public SnapshotResponse takeSnapshotAsync(SnapshotDescription snapshot) throws IOException,
3294       SnapshotCreationException {
3295     ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
3296     final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot)
3297         .build();
3298     // run the snapshot on the master
3299     return executeCallable(new MasterCallable<SnapshotResponse>(getConnection()) {
3300       @Override
3301       public SnapshotResponse call(int callTimeout) throws ServiceException {
3302         return master.snapshot(null, request);
3303       }
3304     });
3305   }
3306 
3307   /**
3308    * Check the current state of the passed snapshot.
3309    * <p>
3310    * There are three possible states:
3311    * <ol>
3312    * <li>running - returns <tt>false</tt></li>
3313    * <li>finished - returns <tt>true</tt></li>
3314    * <li>finished with error - throws the exception that caused the snapshot to fail</li>
3315    * </ol>
3316    * <p>
3317    * The cluster only knows about the most recent snapshot. Therefore, if another snapshot has been
3318    * run/started since the snapshot your are checking, you will recieve an
3319    * {@link UnknownSnapshotException}.
3320    * @param snapshot description of the snapshot to check
3321    * @return <tt>true</tt> if the snapshot is completed, <tt>false</tt> if the snapshot is still
3322    *         running
3323    * @throws IOException if we have a network issue
3324    * @throws HBaseSnapshotException if the snapshot failed
3325    * @throws UnknownSnapshotException if the requested snapshot is unknown
3326    */
3327   @Override
3328   public boolean isSnapshotFinished(final SnapshotDescription snapshot)
3329       throws IOException, HBaseSnapshotException, UnknownSnapshotException {
3330 
3331     return executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection()) {
3332       @Override
3333       public IsSnapshotDoneResponse call(int callTimeout) throws ServiceException {
3334         return master.isSnapshotDone(null,
3335           IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build());
3336       }
3337     }).getDone();
3338   }
3339 
3340   /**
3341    * Restore the specified snapshot on the original table. (The table must be disabled)
3342    * If the "hbase.snapshot.restore.take.failsafe.snapshot" configuration property
3343    * is set to true, a snapshot of the current table is taken
3344    * before executing the restore operation.
3345    * In case of restore failure, the failsafe snapshot will be restored.
3346    * If the restore completes without problem the failsafe snapshot is deleted.
3347    *
3348    * @param snapshotName name of the snapshot to restore
3349    * @throws IOException if a remote or network exception occurs
3350    * @throws RestoreSnapshotException if snapshot failed to be restored
3351    * @throws IllegalArgumentException if the restore request is formatted incorrectly
3352    */
3353   @Override
3354   public void restoreSnapshot(final byte[] snapshotName)
3355       throws IOException, RestoreSnapshotException {
3356     restoreSnapshot(Bytes.toString(snapshotName));
3357   }
3358 
3359   /**
3360    * Restore the specified snapshot on the original table. (The table must be disabled)
3361    * If the "hbase.snapshot.restore.take.failsafe.snapshot" configuration property
3362    * is set to true, a snapshot of the current table is taken
3363    * before executing the restore operation.
3364    * In case of restore failure, the failsafe snapshot will be restored.
3365    * If the restore completes without problem the failsafe snapshot is deleted.
3366    *
3367    * @param snapshotName name of the snapshot to restore
3368    * @throws IOException if a remote or network exception occurs
3369    * @throws RestoreSnapshotException if snapshot failed to be restored
3370    * @throws IllegalArgumentException if the restore request is formatted incorrectly
3371    */
3372   @Override
3373   public void restoreSnapshot(final String snapshotName)
3374       throws IOException, RestoreSnapshotException {
3375     boolean takeFailSafeSnapshot =
3376       conf.getBoolean("hbase.snapshot.restore.take.failsafe.snapshot", false);
3377     restoreSnapshot(snapshotName, takeFailSafeSnapshot);
3378   }
3379 
3380   /**
3381    * Restore the specified snapshot on the original table. (The table must be disabled)
3382    * If 'takeFailSafeSnapshot' is set to true, a snapshot of the current table is taken
3383    * before executing the restore operation.
3384    * In case of restore failure, the failsafe snapshot will be restored.
3385    * If the restore completes without problem the failsafe snapshot is deleted.
3386    *
3387    * The failsafe snapshot name is configurable by using the property
3388    * "hbase.snapshot.restore.failsafe.name".
3389    *
3390    * @param snapshotName name of the snapshot to restore
3391    * @param takeFailSafeSnapshot true if the failsafe snapshot should be taken
3392    * @throws IOException if a remote or network exception occurs
3393    * @throws RestoreSnapshotException if snapshot failed to be restored
3394    * @throws IllegalArgumentException if the restore request is formatted incorrectly
3395    */
3396   @Override
3397   public void restoreSnapshot(final byte[] snapshotName, final boolean takeFailSafeSnapshot)
3398       throws IOException, RestoreSnapshotException {
3399     restoreSnapshot(Bytes.toString(snapshotName), takeFailSafeSnapshot);
3400   }
3401 
3402   /**
3403    * Restore the specified snapshot on the original table. (The table must be disabled)
3404    * If 'takeFailSafeSnapshot' is set to true, a snapshot of the current table is taken
3405    * before executing the restore operation.
3406    * In case of restore failure, the failsafe snapshot will be restored.
3407    * If the restore completes without problem the failsafe snapshot is deleted.
3408    *
3409    * The failsafe snapshot name is configurable by using the property
3410    * "hbase.snapshot.restore.failsafe.name".
3411    *
3412    * @param snapshotName name of the snapshot to restore
3413    * @param takeFailSafeSnapshot true if the failsafe snapshot should be taken
3414    * @throws IOException if a remote or network exception occurs
3415    * @throws RestoreSnapshotException if snapshot failed to be restored
3416    * @throws IllegalArgumentException if the restore request is formatted incorrectly
3417    */
3418   @Override
3419   public void restoreSnapshot(final String snapshotName, boolean takeFailSafeSnapshot)
3420       throws IOException, RestoreSnapshotException {
3421     TableName tableName = null;
3422     for (SnapshotDescription snapshotInfo: listSnapshots()) {
3423       if (snapshotInfo.getName().equals(snapshotName)) {
3424         tableName = TableName.valueOf(snapshotInfo.getTable());
3425         break;
3426       }
3427     }
3428 
3429     if (tableName == null) {
3430       throw new RestoreSnapshotException(
3431         "Unable to find the table name for snapshot=" + snapshotName);
3432     }
3433 
3434     // The table does not exists, switch to clone.
3435     if (!tableExists(tableName)) {
3436       cloneSnapshot(snapshotName, tableName);
3437       return;
3438     }
3439 
3440     // Check if the table is disabled
3441     if (!isTableDisabled(tableName)) {
3442       throw new TableNotDisabledException(tableName);
3443     }
3444 
3445     // Take a snapshot of the current state
3446     String failSafeSnapshotSnapshotName = null;
3447     if (takeFailSafeSnapshot) {
3448       failSafeSnapshotSnapshotName = conf.get("hbase.snapshot.restore.failsafe.name",
3449         "hbase-failsafe-{snapshot.name}-{restore.timestamp}");
3450       failSafeSnapshotSnapshotName = failSafeSnapshotSnapshotName
3451         .replace("{snapshot.name}", snapshotName)
3452         .replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.'))
3453         .replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTime()));
3454       LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
3455       snapshot(failSafeSnapshotSnapshotName, tableName);
3456     }
3457 
3458     try {
3459       // Restore snapshot
3460       internalRestoreSnapshot(snapshotName, tableName);
3461     } catch (IOException e) {
3462       // Somthing went wrong during the restore...
3463       // if the pre-restore snapshot is available try to rollback
3464       if (takeFailSafeSnapshot) {
3465         try {
3466           internalRestoreSnapshot(failSafeSnapshotSnapshotName, tableName);
3467           String msg = "Restore snapshot=" + snapshotName +
3468             " failed. Rollback to snapshot=" + failSafeSnapshotSnapshotName + " succeeded.";
3469           LOG.error(msg, e);
3470           throw new RestoreSnapshotException(msg, e);
3471         } catch (IOException ex) {
3472           String msg = "Failed to restore and rollback to snapshot=" + failSafeSnapshotSnapshotName;
3473           LOG.error(msg, ex);
3474           throw new RestoreSnapshotException(msg, e);
3475         }
3476       } else {
3477         throw new RestoreSnapshotException("Failed to restore snapshot=" + snapshotName, e);
3478       }
3479     }
3480 
3481     // If the restore is succeeded, delete the pre-restore snapshot
3482     if (takeFailSafeSnapshot) {
3483       try {
3484         LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
3485         deleteSnapshot(failSafeSnapshotSnapshotName);
3486       } catch (IOException e) {
3487         LOG.error("Unable to remove the failsafe snapshot: " + failSafeSnapshotSnapshotName, e);
3488       }
3489     }
3490   }
3491 
3492   /**
3493    * Create a new table by cloning the snapshot content.
3494    *
3495    * @param snapshotName name of the snapshot to be cloned
3496    * @param tableName name of the table where the snapshot will be restored
3497    * @throws IOException if a remote or network exception occurs
3498    * @throws TableExistsException if table to be created already exists
3499    * @throws RestoreSnapshotException if snapshot failed to be cloned
3500    * @throws IllegalArgumentException if the specified table has not a valid name
3501    */
3502   public void cloneSnapshot(final byte[] snapshotName, final byte[] tableName)
3503       throws IOException, TableExistsException, RestoreSnapshotException {
3504     cloneSnapshot(Bytes.toString(snapshotName), TableName.valueOf(tableName));
3505   }
3506 
3507   /**
3508    * Create a new table by cloning the snapshot content.
3509    *
3510    * @param snapshotName name of the snapshot to be cloned
3511    * @param tableName name of the table where the snapshot will be restored
3512    * @throws IOException if a remote or network exception occurs
3513    * @throws TableExistsException if table to be created already exists
3514    * @throws RestoreSnapshotException if snapshot failed to be cloned
3515    * @throws IllegalArgumentException if the specified table has not a valid name
3516    */
3517   @Override
3518   public void cloneSnapshot(final byte[] snapshotName, final TableName tableName)
3519       throws IOException, TableExistsException, RestoreSnapshotException {
3520     cloneSnapshot(Bytes.toString(snapshotName), tableName);
3521   }
3522 
3523 
3524 
3525   /**
3526    * Create a new table by cloning the snapshot content.
3527    *
3528    * @param snapshotName name of the snapshot to be cloned
3529    * @param tableName name of the table where the snapshot will be restored
3530    * @throws IOException if a remote or network exception occurs
3531    * @throws TableExistsException if table to be created already exists
3532    * @throws RestoreSnapshotException if snapshot failed to be cloned
3533    * @throws IllegalArgumentException if the specified table has not a valid name
3534    */
3535   public void cloneSnapshot(final String snapshotName, final String tableName)
3536       throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
3537     cloneSnapshot(snapshotName, TableName.valueOf(tableName));
3538   }
3539 
3540   /**
3541    * Create a new table by cloning the snapshot content.
3542    *
3543    * @param snapshotName name of the snapshot to be cloned
3544    * @param tableName name of the table where the snapshot will be restored
3545    * @throws IOException if a remote or network exception occurs
3546    * @throws TableExistsException if table to be created already exists
3547    * @throws RestoreSnapshotException if snapshot failed to be cloned
3548    * @throws IllegalArgumentException if the specified table has not a valid name
3549    */
3550   @Override
3551   public void cloneSnapshot(final String snapshotName, final TableName tableName)
3552       throws IOException, TableExistsException, RestoreSnapshotException {
3553     if (tableExists(tableName)) {
3554       throw new TableExistsException(tableName);
3555     }
3556     internalRestoreSnapshot(snapshotName, tableName);
3557     waitUntilTableIsEnabled(tableName);
3558   }
3559 
3560   /**
3561    * Execute a distributed procedure on a cluster synchronously with return data
3562    *
3563    * @param signature A distributed procedure is uniquely identified
3564    * by its signature (default the root ZK node name of the procedure).
3565    * @param instance The instance name of the procedure. For some procedures, this parameter is
3566    * optional.
3567    * @param props Property/Value pairs of properties passing to the procedure
3568    * @return data returned after procedure execution. null if no return data.
3569    * @throws IOException
3570    */
3571   @Override
3572   public byte[] execProcedureWithRet(String signature, String instance,
3573       Map<String, String> props) throws IOException {
3574     ProcedureDescription.Builder builder = ProcedureDescription.newBuilder();
3575     builder.setSignature(signature).setInstance(instance);
3576     for (Entry<String, String> entry : props.entrySet()) {
3577       NameStringPair pair = NameStringPair.newBuilder().setName(entry.getKey())
3578           .setValue(entry.getValue()).build();
3579       builder.addConfiguration(pair);
3580     }
3581 
3582     final ExecProcedureRequest request = ExecProcedureRequest.newBuilder()
3583         .setProcedure(builder.build()).build();
3584     // run the procedure on the master
3585     ExecProcedureResponse response = executeCallable(new MasterCallable<ExecProcedureResponse>(
3586         getConnection()) {
3587       @Override
3588       public ExecProcedureResponse call(int callTimeout) throws ServiceException {
3589         return master.execProcedureWithRet(null, request);
3590       }
3591     });
3592 
3593     return response.hasReturnData() ? response.getReturnData().toByteArray() : null;
3594   }
3595   /**
3596    * Execute a distributed procedure on a cluster.
3597    *
3598    * @param signature A distributed procedure is uniquely identified
3599    * by its signature (default the root ZK node name of the procedure).
3600    * @param instance The instance name of the procedure. For some procedures, this parameter is
3601    * optional.
3602    * @param props Property/Value pairs of properties passing to the procedure
3603    * @throws IOException
3604    */
3605   @Override
3606   public void execProcedure(String signature, String instance,
3607       Map<String, String> props) throws IOException {
3608     ProcedureDescription.Builder builder = ProcedureDescription.newBuilder();
3609     builder.setSignature(signature).setInstance(instance);
3610     for (Entry<String, String> entry : props.entrySet()) {
3611       NameStringPair pair = NameStringPair.newBuilder().setName(entry.getKey())
3612           .setValue(entry.getValue()).build();
3613       builder.addConfiguration(pair);
3614     }
3615 
3616     final ExecProcedureRequest request = ExecProcedureRequest.newBuilder()
3617         .setProcedure(builder.build()).build();
3618     // run the procedure on the master
3619     ExecProcedureResponse response = executeCallable(new MasterCallable<ExecProcedureResponse>(
3620         getConnection()) {
3621       @Override
3622       public ExecProcedureResponse call(int callTimeout) throws ServiceException {
3623         return master.execProcedure(null, request);
3624       }
3625     });
3626 
3627     long start = EnvironmentEdgeManager.currentTime();
3628     long max = response.getExpectedTimeout();
3629     long maxPauseTime = max / this.numRetries;
3630     int tries = 0;
3631     LOG.debug("Waiting a max of " + max + " ms for procedure '" +
3632         signature + " : " + instance + "'' to complete. (max " + maxPauseTime + " ms per retry)");
3633     boolean done = false;
3634     while (tries == 0
3635         || ((EnvironmentEdgeManager.currentTime() - start) < max && !done)) {
3636       try {
3637         // sleep a backoff <= pauseTime amount
3638         long sleep = getPauseTime(tries++);
3639         sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3640         LOG.debug("(#" + tries + ") Sleeping: " + sleep +
3641           "ms while waiting for procedure completion.");
3642         Thread.sleep(sleep);
3643       } catch (InterruptedException e) {
3644         throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
3645       }
3646       LOG.debug("Getting current status of procedure from master...");
3647       done = isProcedureFinished(signature, instance, props);
3648     }
3649     if (!done) {
3650       throw new IOException("Procedure '" + signature + " : " + instance
3651           + "' wasn't completed in expectedTime:" + max + " ms");
3652     }
3653   }
3654 
3655   /**
3656    * Check the current state of the specified procedure.
3657    * <p>
3658    * There are three possible states:
3659    * <ol>
3660    * <li>running - returns <tt>false</tt></li>
3661    * <li>finished - returns <tt>true</tt></li>
3662    * <li>finished with error - throws the exception that caused the procedure to fail</li>
3663    * </ol>
3664    * <p>
3665    *
3666    * @param signature The signature that uniquely identifies a procedure
3667    * @param instance The instance name of the procedure
3668    * @param props Property/Value pairs of properties passing to the procedure
3669    * @return true if the specified procedure is finished successfully, false if it is still running
3670    * @throws IOException if the specified procedure finished with error
3671    */
3672   @Override
3673   public boolean isProcedureFinished(String signature, String instance, Map<String, String> props)
3674       throws IOException {
3675     final ProcedureDescription.Builder builder = ProcedureDescription.newBuilder();
3676     builder.setSignature(signature).setInstance(instance);
3677     for (Entry<String, String> entry : props.entrySet()) {
3678       NameStringPair pair = NameStringPair.newBuilder().setName(entry.getKey())
3679           .setValue(entry.getValue()).build();
3680       builder.addConfiguration(pair);
3681     }
3682     final ProcedureDescription desc = builder.build();
3683     return executeCallable(
3684         new MasterCallable<IsProcedureDoneResponse>(getConnection()) {
3685           @Override
3686           public IsProcedureDoneResponse call(int callTimeout) throws ServiceException {
3687             return master.isProcedureDone(null, IsProcedureDoneRequest
3688                 .newBuilder().setProcedure(desc).build());
3689           }
3690         }).getDone();
3691   }
3692 
3693   /**
3694    * Execute Restore/Clone snapshot and wait for the server to complete (blocking).
3695    * To check if the cloned table exists, use {@link #isTableAvailable} -- it is not safe to
3696    * create an HTable instance to this table before it is available.
3697    * @param snapshotName snapshot to restore
3698    * @param tableName table name to restore the snapshot on
3699    * @throws IOException if a remote or network exception occurs
3700    * @throws RestoreSnapshotException if snapshot failed to be restored
3701    * @throws IllegalArgumentException if the restore request is formatted incorrectly
3702    */
3703   private void internalRestoreSnapshot(final String snapshotName, final TableName
3704       tableName)
3705       throws IOException, RestoreSnapshotException {
3706     SnapshotDescription snapshot = SnapshotDescription.newBuilder()
3707         .setName(snapshotName).setTable(tableName.getNameAsString()).build();
3708 
3709     // actually restore the snapshot
3710     internalRestoreSnapshotAsync(snapshot);
3711 
3712     final IsRestoreSnapshotDoneRequest request = IsRestoreSnapshotDoneRequest.newBuilder()
3713         .setSnapshot(snapshot).build();
3714     IsRestoreSnapshotDoneResponse done = IsRestoreSnapshotDoneResponse.newBuilder()
3715         .setDone(false).buildPartial();
3716     final long maxPauseTime = 5000;
3717     int tries = 0;
3718     while (!done.getDone()) {
3719       try {
3720         // sleep a backoff <= pauseTime amount
3721         long sleep = getPauseTime(tries++);
3722         sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3723         LOG.debug(tries + ") Sleeping: " + sleep + " ms while we wait for snapshot restore to complete.");
3724         Thread.sleep(sleep);
3725       } catch (InterruptedException e) {
3726         throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
3727       }
3728       LOG.debug("Getting current status of snapshot restore from master...");
3729       done = executeCallable(new MasterCallable<IsRestoreSnapshotDoneResponse>(
3730           getConnection()) {
3731         @Override
3732         public IsRestoreSnapshotDoneResponse call(int callTimeout) throws ServiceException {
3733           return master.isRestoreSnapshotDone(null, request);
3734         }
3735       });
3736     }
3737     if (!done.getDone()) {
3738       throw new RestoreSnapshotException("Snapshot '" + snapshot.getName() + "' wasn't restored.");
3739     }
3740   }
3741 
3742   /**
3743    * Execute Restore/Clone snapshot and wait for the server to complete (asynchronous)
3744    * <p>
3745    * Only a single snapshot should be restored at a time, or results may be undefined.
3746    * @param snapshot snapshot to restore
3747    * @return response from the server indicating the max time to wait for the snapshot
3748    * @throws IOException if a remote or network exception occurs
3749    * @throws RestoreSnapshotException if snapshot failed to be restored
3750    * @throws IllegalArgumentException if the restore request is formatted incorrectly
3751    */
3752   private RestoreSnapshotResponse internalRestoreSnapshotAsync(final SnapshotDescription snapshot)
3753       throws IOException, RestoreSnapshotException {
3754     ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
3755 
3756     final RestoreSnapshotRequest request = RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot)
3757         .build();
3758 
3759     // run the snapshot restore on the master
3760     return executeCallable(new MasterCallable<RestoreSnapshotResponse>(getConnection()) {
3761       @Override
3762       public RestoreSnapshotResponse call(int callTimeout) throws ServiceException {
3763         return master.restoreSnapshot(null, request);
3764       }
3765     });
3766   }
3767 
3768   /**
3769    * List completed snapshots.
3770    * @return a list of snapshot descriptors for completed snapshots
3771    * @throws IOException if a network error occurs
3772    */
3773   @Override
3774   public List<SnapshotDescription> listSnapshots() throws IOException {
3775     return executeCallable(new MasterCallable<List<SnapshotDescription>>(getConnection()) {
3776       @Override
3777       public List<SnapshotDescription> call(int callTimeout) throws ServiceException {
3778         return master.getCompletedSnapshots(null, GetCompletedSnapshotsRequest.newBuilder().build())
3779             .getSnapshotsList();
3780       }
3781     });
3782   }
3783 
3784   /**
3785    * List all the completed snapshots matching the given regular expression.
3786    *
3787    * @param regex The regular expression to match against
3788    * @return - returns a List of SnapshotDescription
3789    * @throws IOException if a remote or network exception occurs
3790    */
3791   @Override
3792   public List<SnapshotDescription> listSnapshots(String regex) throws IOException {
3793     return listSnapshots(Pattern.compile(regex));
3794   }
3795 
3796   /**
3797    * List all the completed snapshots matching the given pattern.
3798    *
3799    * @param pattern The compiled regular expression to match against
3800    * @return - returns a List of SnapshotDescription
3801    * @throws IOException if a remote or network exception occurs
3802    */
3803   @Override
3804   public List<SnapshotDescription> listSnapshots(Pattern pattern) throws IOException {
3805     List<SnapshotDescription> matched = new LinkedList<SnapshotDescription>();
3806     List<SnapshotDescription> snapshots = listSnapshots();
3807     for (SnapshotDescription snapshot : snapshots) {
3808       if (pattern.matcher(snapshot.getName()).matches()) {
3809         matched.add(snapshot);
3810       }
3811     }
3812     return matched;
3813   }
3814 
3815   /**
3816    * Delete an existing snapshot.
3817    * @param snapshotName name of the snapshot
3818    * @throws IOException if a remote or network exception occurs
3819    */
3820   @Override
3821   public void deleteSnapshot(final byte[] snapshotName) throws IOException {
3822     deleteSnapshot(Bytes.toString(snapshotName));
3823   }
3824 
3825   /**
3826    * Delete an existing snapshot.
3827    * @param snapshotName name of the snapshot
3828    * @throws IOException if a remote or network exception occurs
3829    */
3830   @Override
3831   public void deleteSnapshot(final String snapshotName) throws IOException {
3832     // make sure the snapshot is possibly valid
3833     TableName.isLegalFullyQualifiedTableName(Bytes.toBytes(snapshotName));
3834     // do the delete
3835     executeCallable(new MasterCallable<Void>(getConnection()) {
3836       @Override
3837       public Void call(int callTimeout) throws ServiceException {
3838         master.deleteSnapshot(null,
3839           DeleteSnapshotRequest.newBuilder().
3840             setSnapshot(SnapshotDescription.newBuilder().setName(snapshotName).build()).build()
3841         );
3842         return null;
3843       }
3844     });
3845   }
3846 
3847   /**
3848    * Delete existing snapshots whose names match the pattern passed.
3849    * @param regex The regular expression to match against
3850    * @throws IOException if a remote or network exception occurs
3851    */
3852   @Override
3853   public void deleteSnapshots(final String regex) throws IOException {
3854     deleteSnapshots(Pattern.compile(regex));
3855   }
3856 
3857   /**
3858    * Delete existing snapshots whose names match the pattern passed.
3859    * @param pattern pattern for names of the snapshot to match
3860    * @throws IOException if a remote or network exception occurs
3861    */
3862   @Override
3863   public void deleteSnapshots(final Pattern pattern) throws IOException {
3864     List<SnapshotDescription> snapshots = listSnapshots(pattern);
3865     for (final SnapshotDescription snapshot : snapshots) {
3866       try {
3867         internalDeleteSnapshot(snapshot);
3868       } catch (IOException ex) {
3869         LOG.info(
3870           "Failed to delete snapshot " + snapshot.getName() + " for table " + snapshot.getTable(),
3871           ex);
3872       }
3873     }
3874   }
3875 
3876   private void internalDeleteSnapshot(final SnapshotDescription snapshot) throws IOException {
3877     executeCallable(new MasterCallable<Void>(getConnection()) {
3878       @Override
3879       public Void call(int callTimeout) throws ServiceException {
3880         this.master.deleteSnapshot(null, DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot)
3881             .build());
3882         return null;
3883       }
3884     });
3885   }
3886 
3887   /**
3888    * Apply the new quota settings.
3889    * @param quota the quota settings
3890    * @throws IOException if a remote or network exception occurs
3891    */
3892   @Override
3893   public void setQuota(final QuotaSettings quota) throws IOException {
3894     executeCallable(new MasterCallable<Void>(getConnection()) {
3895       @Override
3896       public Void call(int callTimeout) throws ServiceException {
3897         this.master.setQuota(null, QuotaSettings.buildSetQuotaRequestProto(quota));
3898         return null;
3899       }
3900     });
3901   }
3902 
3903   /**
3904    * Return a Quota Scanner to list the quotas based on the filter.
3905    * @param filter the quota settings filter
3906    * @return the quota scanner
3907    * @throws IOException if a remote or network exception occurs
3908    */
3909   @Override
3910   public QuotaRetriever getQuotaRetriever(final QuotaFilter filter) throws IOException {
3911     return QuotaRetriever.open(conf, filter);
3912   }
3913 
3914   private <V> V executeCallable(MasterCallable<V> callable) throws IOException {
3915     RpcRetryingCaller<V> caller = rpcCallerFactory.newCaller();
3916     try {
3917       return caller.callWithRetries(callable, operationTimeout);
3918     } finally {
3919       callable.close();
3920     }
3921   }
3922 
3923   /**
3924    * Creates and returns a {@link com.google.protobuf.RpcChannel} instance
3925    * connected to the active master.
3926    *
3927    * <p>
3928    * The obtained {@link com.google.protobuf.RpcChannel} instance can be used to access a published
3929    * coprocessor {@link com.google.protobuf.Service} using standard protobuf service invocations:
3930    * </p>
3931    *
3932    * <div style="background-color: #cccccc; padding: 2px">
3933    * <blockquote><pre>
3934    * CoprocessorRpcChannel channel = myAdmin.coprocessorService();
3935    * MyService.BlockingInterface service = MyService.newBlockingStub(channel);
3936    * MyCallRequest request = MyCallRequest.newBuilder()
3937    *     ...
3938    *     .build();
3939    * MyCallResponse response = service.myCall(null, request);
3940    * </pre></blockquote></div>
3941    *
3942    * @return A MasterCoprocessorRpcChannel instance
3943    */
3944   @Override
3945   public CoprocessorRpcChannel coprocessorService() {
3946     return new MasterCoprocessorRpcChannel(connection);
3947   }
3948 
3949   /**
3950    * Simple {@link Abortable}, throwing RuntimeException on abort.
3951    */
3952   private static class ThrowableAbortable implements Abortable {
3953 
3954     @Override
3955     public void abort(String why, Throwable e) {
3956       throw new RuntimeException(why, e);
3957     }
3958 
3959     @Override
3960     public boolean isAborted() {
3961       return true;
3962     }
3963   }
3964 
3965   /**
3966    * Creates and returns a {@link com.google.protobuf.RpcChannel} instance
3967    * connected to the passed region server.
3968    *
3969    * <p>
3970    * The obtained {@link com.google.protobuf.RpcChannel} instance can be used to access a published
3971    * coprocessor {@link com.google.protobuf.Service} using standard protobuf service invocations:
3972    * </p>
3973    *
3974    * <div style="background-color: #cccccc; padding: 2px">
3975    * <blockquote><pre>
3976    * CoprocessorRpcChannel channel = myAdmin.coprocessorService(serverName);
3977    * MyService.BlockingInterface service = MyService.newBlockingStub(channel);
3978    * MyCallRequest request = MyCallRequest.newBuilder()
3979    *     ...
3980    *     .build();
3981    * MyCallResponse response = service.myCall(null, request);
3982    * </pre></blockquote></div>
3983    *
3984    * @param sn the server name to which the endpoint call is made
3985    * @return A RegionServerCoprocessorRpcChannel instance
3986    */
3987   @Override
3988   public CoprocessorRpcChannel coprocessorService(ServerName sn) {
3989     return new RegionServerCoprocessorRpcChannel(connection, sn);
3990   }
3991 
3992   @Override
3993   public void updateConfiguration(ServerName server) throws IOException {
3994     try {
3995       this.connection.getAdmin(server).updateConfiguration(null,
3996         UpdateConfigurationRequest.getDefaultInstance());
3997     } catch (ServiceException e) {
3998       throw ProtobufUtil.getRemoteException(e);
3999     }
4000   }
4001 
4002   @Override
4003   public void updateConfiguration() throws IOException {
4004     for (ServerName server : this.getClusterStatus().getServers()) {
4005       updateConfiguration(server);
4006     }
4007   }
4008 
4009   @Override
4010   public int getMasterInfoPort() throws IOException {
4011     // TODO: Fix!  Reaching into internal implementation!!!!
4012     ConnectionManager.HConnectionImplementation connection =
4013         (ConnectionManager.HConnectionImplementation)this.connection;
4014     ZooKeeperKeepAliveConnection zkw = connection.getKeepAliveZooKeeperWatcher();
4015     try {
4016       return MasterAddressTracker.getMasterInfoPort(zkw);
4017     } catch (KeeperException e) {
4018       throw new IOException("Failed to get master info port from MasterAddressTracker", e);
4019     }
4020   }
4021 
4022   @Override
4023   public long getLastMajorCompactionTimestamp(final TableName tableName) throws IOException {
4024     return executeCallable(new MasterCallable<Long>(getConnection()) {
4025       @Override
4026       public Long call(int callTimeout) throws ServiceException {
4027         MajorCompactionTimestampRequest req =
4028             MajorCompactionTimestampRequest.newBuilder()
4029                 .setTableName(ProtobufUtil.toProtoTableName(tableName)).build();
4030         return master.getLastMajorCompactionTimestamp(null, req).getCompactionTimestamp();
4031       }
4032     });
4033   }
4034 
4035   @Override
4036   public long getLastMajorCompactionTimestampForRegion(final byte[] regionName) throws IOException {
4037     return executeCallable(new MasterCallable<Long>(getConnection()) {
4038       @Override
4039       public Long call(int callTimeout) throws ServiceException {
4040         MajorCompactionTimestampForRegionRequest req =
4041             MajorCompactionTimestampForRegionRequest
4042                 .newBuilder()
4043                 .setRegion(
4044                   RequestConverter
4045                       .buildRegionSpecifier(RegionSpecifierType.REGION_NAME, regionName)).build();
4046         return master.getLastMajorCompactionTimestampForRegion(null, req).getCompactionTimestamp();
4047       }
4048     });
4049   }
4050 
4051   /**
4052    * Future that waits on a procedure result.
4053    * Returned by the async version of the Admin calls,
4054    * and used internally by the sync calls to wait on the result of the procedure.
4055    */
4056   @InterfaceAudience.Private
4057   @InterfaceStability.Evolving
4058   protected static class ProcedureFuture<V> implements Future<V> {
4059     private ExecutionException exception = null;
4060     private boolean procResultFound = false;
4061     private boolean done = false;
4062     private V result = null;
4063 
4064     private final HBaseAdmin admin;
4065     private final Long procId;
4066 
4067     public ProcedureFuture(final HBaseAdmin admin, final Long procId) {
4068       this.admin = admin;
4069       this.procId = procId;
4070     }
4071 
4072     @Override
4073     public boolean cancel(boolean mayInterruptIfRunning) {
4074       throw new UnsupportedOperationException();
4075     }
4076 
4077     @Override
4078     public boolean isCancelled() {
4079       // TODO: Abort not implemented yet
4080       return false;
4081     }
4082 
4083     @Override
4084     public V get() throws InterruptedException, ExecutionException {
4085       // TODO: should we ever spin forever?
4086       throw new UnsupportedOperationException();
4087     }
4088 
4089     @Override
4090     public V get(long timeout, TimeUnit unit)
4091         throws InterruptedException, ExecutionException, TimeoutException {
4092       if (!done) {
4093         long deadlineTs = EnvironmentEdgeManager.currentTime() + unit.toMillis(timeout);
4094         try {
4095           try {
4096             // if the master support procedures, try to wait the result
4097             if (procId != null) {
4098               result = waitProcedureResult(procId, deadlineTs);
4099             }
4100             // if we don't have a proc result, try the compatibility wait
4101             if (!procResultFound) {
4102               result = waitOperationResult(deadlineTs);
4103             }
4104             result = postOperationResult(result, deadlineTs);
4105             done = true;
4106           } catch (IOException e) {
4107             result = postOpeartionFailure(e, deadlineTs);
4108             done = true;
4109           }
4110         } catch (IOException e) {
4111           exception = new ExecutionException(e);
4112           done = true;
4113         }
4114       }
4115       if (exception != null) {
4116         throw exception;
4117       }
4118       return result;
4119     }
4120 
4121     @Override
4122     public boolean isDone() {
4123       return done;
4124     }
4125 
4126     protected HBaseAdmin getAdmin() {
4127       return admin;
4128     }
4129 
4130     private V waitProcedureResult(long procId, long deadlineTs)
4131         throws IOException, TimeoutException, InterruptedException {
4132       GetProcedureResultRequest request = GetProcedureResultRequest.newBuilder()
4133           .setProcId(procId)
4134           .build();
4135 
4136       int tries = 0;
4137       IOException serviceEx = null;
4138       while (EnvironmentEdgeManager.currentTime() < deadlineTs) {
4139         GetProcedureResultResponse response = null;
4140         try {
4141           // Try to fetch the result
4142           response = getProcedureResult(request);
4143         } catch (IOException e) {
4144           serviceEx = unwrapException(e);
4145 
4146           // the master may be down
4147           LOG.warn("failed to get the procedure result procId=" + procId, serviceEx);
4148 
4149           // Not much to do, if we have a DoNotRetryIOException
4150           if (serviceEx instanceof DoNotRetryIOException) {
4151             // TODO: looks like there is no way to unwrap this exception and get the proper
4152             // UnsupportedOperationException aside from looking at the message.
4153             // anyway, if we fail here we just failover to the compatibility side
4154             // and that is always a valid solution.
4155             LOG.warn("Proc-v2 is unsupported on this master: " + serviceEx.getMessage(), serviceEx);
4156             procResultFound = false;
4157             return null;
4158           }
4159         }
4160 
4161         // If the procedure is no longer running, we should have a result
4162         if (response != null && response.getState() != GetProcedureResultResponse.State.RUNNING) {
4163           procResultFound = response.getState() != GetProcedureResultResponse.State.NOT_FOUND;
4164           return convertResult(response);
4165         }
4166 
4167         try {
4168           Thread.sleep(getAdmin().getPauseTime(tries++));
4169         } catch (InterruptedException e) {
4170           throw new InterruptedException(
4171             "Interrupted while waiting for the result of proc " + procId);
4172         }
4173       }
4174       if (serviceEx != null) {
4175         throw serviceEx;
4176       } else {
4177         throw new TimeoutException("The procedure " + procId + " is still running");
4178       }
4179     }
4180 
4181     private static IOException unwrapException(IOException e) {
4182       if (e instanceof RemoteException) {
4183         return ((RemoteException)e).unwrapRemoteException();
4184       }
4185       return e;
4186     }
4187 
4188     protected GetProcedureResultResponse getProcedureResult(final GetProcedureResultRequest request)
4189         throws IOException {
4190       return admin.executeCallable(new MasterCallable<GetProcedureResultResponse>(
4191           admin.getConnection()) {
4192         @Override
4193         public GetProcedureResultResponse call(int callTimeout) throws ServiceException {
4194           return master.getProcedureResult(null, request);
4195         }
4196       });
4197     }
4198 
4199     /**
4200      * Convert the procedure result response to a specified type.
4201      * @param response the procedure result object to parse
4202      * @return the result data of the procedure.
4203      */
4204     protected V convertResult(final GetProcedureResultResponse response) throws IOException {
4205       if (response.hasException()) {
4206         throw ForeignExceptionUtil.toIOException(response.getException());
4207       }
4208       return null;
4209     }
4210 
4211     /**
4212      * Fallback implementation in case the procedure is not supported by the server.
4213      * It should try to wait until the operation is completed.
4214      * @param deadlineTs the timestamp after which this method should throw a TimeoutException
4215      * @return the result data of the operation
4216      */
4217     protected V waitOperationResult(final long deadlineTs)
4218         throws IOException, TimeoutException {
4219       return null;
4220     }
4221 
4222     /**
4223      * Called after the operation is completed and the result fetched.
4224      * this allows to perform extra steps after the procedure is completed.
4225      * it allows to apply transformations to the result that will be returned by get().
4226      * @param result the result of the procedure
4227      * @param deadlineTs the timestamp after which this method should throw a TimeoutException
4228      * @return the result of the procedure, which may be the same as the passed one
4229      */
4230     protected V postOperationResult(final V result, final long deadlineTs)
4231         throws IOException, TimeoutException {
4232       return result;
4233     }
4234 
4235     /**
4236      * Called after the operation is terminated with a failure.
4237      * this allows to perform extra steps after the procedure is terminated.
4238      * it allows to apply transformations to the result that will be returned by get().
4239      * The default implementation will rethrow the exception
4240      * @param exception the exception got from fetching the result
4241      * @param deadlineTs the timestamp after which this method should throw a TimeoutException
4242      * @return the result of the procedure, which may be the same as the passed one
4243      */
4244     protected V postOpeartionFailure(final IOException exception, final long deadlineTs)
4245         throws IOException, TimeoutException {
4246       throw exception;
4247     }
4248 
4249     protected interface WaitForStateCallable {
4250       boolean checkState(int tries) throws IOException;
4251       void throwInterruptedException() throws InterruptedIOException;
4252       void throwTimeoutException(long elapsed) throws TimeoutException;
4253     }
4254 
4255     protected void waitForState(final long deadlineTs, final WaitForStateCallable callable)
4256         throws IOException, TimeoutException {
4257       int tries = 0;
4258       IOException serverEx = null;
4259       long startTime = EnvironmentEdgeManager.currentTime();
4260       while (EnvironmentEdgeManager.currentTime() < deadlineTs) {
4261         serverEx = null;
4262         try {
4263           if (callable.checkState(tries)) {
4264             return;
4265           }
4266         } catch (IOException e) {
4267           serverEx = e;
4268         }
4269         try {
4270           Thread.sleep(getAdmin().getPauseTime(tries++));
4271         } catch (InterruptedException e) {
4272           callable.throwInterruptedException();
4273         }
4274       }
4275       if (serverEx != null) {
4276         throw unwrapException(serverEx);
4277       } else {
4278         callable.throwTimeoutException(EnvironmentEdgeManager.currentTime() - startTime);
4279       }
4280     }
4281   }
4282 }