001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import static org.apache.hadoop.hbase.HConstants.HIGH_QOS;
021import static org.apache.hadoop.hbase.TableName.META_TABLE_NAME;
022import static org.apache.hadoop.hbase.util.FutureUtils.addListener;
023import static org.apache.hadoop.hbase.util.FutureUtils.unwrapCompletionException;
024import edu.umd.cs.findbugs.annotations.Nullable;
025import java.io.IOException;
026import java.util.ArrayList;
027import java.util.Arrays;
028import java.util.Collections;
029import java.util.EnumSet;
030import java.util.HashMap;
031import java.util.List;
032import java.util.Map;
033import java.util.Optional;
034import java.util.Set;
035import java.util.concurrent.CompletableFuture;
036import java.util.concurrent.ConcurrentHashMap;
037import java.util.concurrent.ConcurrentLinkedQueue;
038import java.util.concurrent.TimeUnit;
039import java.util.concurrent.atomic.AtomicReference;
040import java.util.function.BiConsumer;
041import java.util.function.Consumer;
042import java.util.function.Function;
043import java.util.function.Supplier;
044import java.util.regex.Pattern;
045import java.util.stream.Collectors;
046import java.util.stream.Stream;
047import org.apache.hadoop.conf.Configuration;
048import org.apache.hadoop.hbase.CacheEvictionStats;
049import org.apache.hadoop.hbase.CacheEvictionStatsAggregator;
050import org.apache.hadoop.hbase.CatalogFamilyFormat;
051import org.apache.hadoop.hbase.ClientMetaTableAccessor;
052import org.apache.hadoop.hbase.ClusterMetrics;
053import org.apache.hadoop.hbase.ClusterMetrics.Option;
054import org.apache.hadoop.hbase.ClusterMetricsBuilder;
055import org.apache.hadoop.hbase.HConstants;
056import org.apache.hadoop.hbase.HRegionLocation;
057import org.apache.hadoop.hbase.NamespaceDescriptor;
058import org.apache.hadoop.hbase.RegionLocations;
059import org.apache.hadoop.hbase.RegionMetrics;
060import org.apache.hadoop.hbase.RegionMetricsBuilder;
061import org.apache.hadoop.hbase.ServerName;
062import org.apache.hadoop.hbase.TableExistsException;
063import org.apache.hadoop.hbase.TableName;
064import org.apache.hadoop.hbase.TableNotDisabledException;
065import org.apache.hadoop.hbase.TableNotEnabledException;
066import org.apache.hadoop.hbase.TableNotFoundException;
067import org.apache.hadoop.hbase.UnknownRegionException;
068import org.apache.hadoop.hbase.client.AsyncRpcRetryingCallerFactory.AdminRequestCallerBuilder;
069import org.apache.hadoop.hbase.client.AsyncRpcRetryingCallerFactory.MasterRequestCallerBuilder;
070import org.apache.hadoop.hbase.client.AsyncRpcRetryingCallerFactory.ServerRequestCallerBuilder;
071import org.apache.hadoop.hbase.client.Scan.ReadType;
072import org.apache.hadoop.hbase.client.replication.ReplicationPeerConfigUtil;
073import org.apache.hadoop.hbase.client.replication.TableCFs;
074import org.apache.hadoop.hbase.client.security.SecurityCapability;
075import org.apache.hadoop.hbase.exceptions.DeserializationException;
076import org.apache.hadoop.hbase.ipc.HBaseRpcController;
077import org.apache.hadoop.hbase.net.Address;
078import org.apache.hadoop.hbase.quotas.QuotaFilter;
079import org.apache.hadoop.hbase.quotas.QuotaSettings;
080import org.apache.hadoop.hbase.quotas.QuotaTableUtil;
081import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot;
082import org.apache.hadoop.hbase.replication.ReplicationException;
083import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
084import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
085import org.apache.hadoop.hbase.replication.SyncReplicationState;
086import org.apache.hadoop.hbase.rsgroup.RSGroupInfo;
087import org.apache.hadoop.hbase.security.access.GetUserPermissionsRequest;
088import org.apache.hadoop.hbase.security.access.Permission;
089import org.apache.hadoop.hbase.security.access.ShadedAccessControlUtil;
090import org.apache.hadoop.hbase.security.access.UserPermission;
091import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
092import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
093import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
094import org.apache.hadoop.hbase.util.Bytes;
095import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
096import org.apache.hadoop.hbase.util.ForeignExceptionUtil;
097import org.apache.hadoop.hbase.util.Pair;
098import org.apache.yetus.audience.InterfaceAudience;
099import org.slf4j.Logger;
100import org.slf4j.LoggerFactory;
101
102import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
103import org.apache.hbase.thirdparty.com.google.protobuf.Message;
104import org.apache.hbase.thirdparty.com.google.protobuf.RpcCallback;
105import org.apache.hbase.thirdparty.com.google.protobuf.RpcChannel;
106import org.apache.hbase.thirdparty.io.netty.util.HashedWheelTimer;
107import org.apache.hbase.thirdparty.io.netty.util.Timeout;
108import org.apache.hbase.thirdparty.io.netty.util.TimerTask;
109import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils;
110
111import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
112import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
113import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos;
114import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.GetUserPermissionsResponse;
115import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.GrantRequest;
116import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.GrantResponse;
117import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.HasUserPermissionsRequest;
118import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.HasUserPermissionsResponse;
119import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.RevokeRequest;
120import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.RevokeResponse;
121import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService;
122import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesRequest;
123import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesResponse;
124import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheRequest;
125import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheResponse;
126import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionRequest;
127import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionResponse;
128import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactionSwitchRequest;
129import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactionSwitchResponse;
130import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionRequest;
131import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionResponse;
132import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
133import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
134import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoRequest;
135import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse;
136import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadRequest;
137import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadResponse;
138import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterRequest;
139import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterResponse;
140import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerRequest;
141import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerResponse;
142import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationRequest;
143import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationResponse;
144import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
145import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.NameStringPair;
146import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ProcedureDescription;
147import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
148import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.TableSchema;
149import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos;
150import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AbortProcedureRequest;
151import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AbortProcedureResponse;
152import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AddColumnRequest;
153import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AddColumnResponse;
154import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AssignRegionRequest;
155import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AssignRegionResponse;
156import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ClearDeadServersRequest;
157import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ClearDeadServersResponse;
158import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateNamespaceRequest;
159import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateNamespaceResponse;
160import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableRequest;
161import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableResponse;
162import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DecommissionRegionServersRequest;
163import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DecommissionRegionServersResponse;
164import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteColumnRequest;
165import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteColumnResponse;
166import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteNamespaceRequest;
167import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteNamespaceResponse;
168import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
169import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteSnapshotResponse;
170import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteTableRequest;
171import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteTableResponse;
172import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DisableTableRequest;
173import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DisableTableResponse;
174import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableCatalogJanitorRequest;
175import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableCatalogJanitorResponse;
176import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableTableRequest;
177import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableTableResponse;
178import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ExecProcedureRequest;
179import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ExecProcedureResponse;
180import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetClusterStatusRequest;
181import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetClusterStatusResponse;
182import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
183import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
184import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetLocksRequest;
185import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetLocksResponse;
186import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest;
187import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetNamespaceDescriptorResponse;
188import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProcedureResultRequest;
189import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProcedureResultResponse;
190import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProceduresRequest;
191import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProceduresResponse;
192import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsRequest;
193import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
194import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableNamesRequest;
195import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableNamesResponse;
196import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsBalancerEnabledRequest;
197import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsBalancerEnabledResponse;
198import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCatalogJanitorEnabledRequest;
199import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCatalogJanitorEnabledResponse;
200import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCleanerChoreEnabledRequest;
201import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCleanerChoreEnabledResponse;
202import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsInMaintenanceModeRequest;
203import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsInMaintenanceModeResponse;
204import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsNormalizerEnabledRequest;
205import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsNormalizerEnabledResponse;
206import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsProcedureDoneRequest;
207import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsProcedureDoneResponse;
208import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsRpcThrottleEnabledRequest;
209import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsRpcThrottleEnabledResponse;
210import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotCleanupEnabledResponse;
211import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
212import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
213import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSplitOrMergeEnabledRequest;
214import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSplitOrMergeEnabledResponse;
215import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListDecommissionedRegionServersRequest;
216import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListDecommissionedRegionServersResponse;
217import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest;
218import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespaceDescriptorsResponse;
219import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespacesRequest;
220import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespacesResponse;
221import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest;
222import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceResponse;
223import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest;
224import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableNamesByNamespaceResponse;
225import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampForRegionRequest;
226import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampRequest;
227import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampResponse;
228import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MasterService;
229import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsRequest;
230import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsResponse;
231import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyColumnRequest;
232import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyColumnResponse;
233import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyNamespaceRequest;
234import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyNamespaceResponse;
235import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyTableRequest;
236import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyTableResponse;
237import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MoveRegionRequest;
238import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MoveRegionResponse;
239import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.NormalizeRequest;
240import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.NormalizeResponse;
241import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.OfflineRegionRequest;
242import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.OfflineRegionResponse;
243import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RecommissionRegionServerRequest;
244import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RecommissionRegionServerResponse;
245import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RestoreSnapshotRequest;
246import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RestoreSnapshotResponse;
247import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCatalogScanRequest;
248import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCatalogScanResponse;
249import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCleanerChoreRequest;
250import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCleanerChoreResponse;
251import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SecurityCapabilitiesRequest;
252import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SecurityCapabilitiesResponse;
253import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetBalancerRunningRequest;
254import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetBalancerRunningResponse;
255import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetCleanerChoreRunningRequest;
256import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetCleanerChoreRunningResponse;
257import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetNormalizerRunningRequest;
258import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetNormalizerRunningResponse;
259import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetQuotaRequest;
260import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetQuotaResponse;
261import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetSnapshotCleanupResponse;
262import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetSplitOrMergeEnabledRequest;
263import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetSplitOrMergeEnabledResponse;
264import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ShutdownRequest;
265import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ShutdownResponse;
266import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SnapshotRequest;
267import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SnapshotResponse;
268import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SplitTableRegionRequest;
269import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SplitTableRegionResponse;
270import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.StopMasterRequest;
271import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.StopMasterResponse;
272import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SwitchExceedThrottleQuotaRequest;
273import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SwitchExceedThrottleQuotaResponse;
274import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SwitchRpcThrottleRequest;
275import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SwitchRpcThrottleResponse;
276import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.TruncateTableRequest;
277import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.TruncateTableResponse;
278import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.UnassignRegionRequest;
279import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.UnassignRegionResponse;
280import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetQuotaStatesRequest;
281import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetQuotaStatesResponse;
282import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaRegionSizesRequest;
283import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaRegionSizesResponse;
284import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaRegionSizesResponse.RegionSizes;
285import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaSnapshotsRequest;
286import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaSnapshotsResponse;
287import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.AddRSGroupRequest;
288import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.AddRSGroupResponse;
289import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.BalanceRSGroupRequest;
290import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.BalanceRSGroupResponse;
291import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetConfiguredNamespacesAndTablesInRSGroupRequest;
292import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetConfiguredNamespacesAndTablesInRSGroupResponse;
293import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetRSGroupInfoOfServerRequest;
294import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetRSGroupInfoOfServerResponse;
295import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetRSGroupInfoOfTableRequest;
296import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetRSGroupInfoOfTableResponse;
297import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetRSGroupInfoRequest;
298import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.GetRSGroupInfoResponse;
299import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.ListRSGroupInfosRequest;
300import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.ListRSGroupInfosResponse;
301import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.ListTablesInRSGroupRequest;
302import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.ListTablesInRSGroupResponse;
303import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.MoveServersRequest;
304import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.MoveServersResponse;
305import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.RemoveRSGroupRequest;
306import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.RemoveRSGroupResponse;
307import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.RemoveServersRequest;
308import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.RemoveServersResponse;
309import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.RenameRSGroupRequest;
310import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.RenameRSGroupResponse;
311import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.UpdateRSGroupConfigRequest;
312import org.apache.hadoop.hbase.shaded.protobuf.generated.RSGroupAdminProtos.UpdateRSGroupConfigResponse;
313import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.AddReplicationPeerRequest;
314import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.AddReplicationPeerResponse;
315import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.DisableReplicationPeerRequest;
316import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.DisableReplicationPeerResponse;
317import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.EnableReplicationPeerRequest;
318import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.EnableReplicationPeerResponse;
319import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.GetReplicationPeerConfigRequest;
320import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.GetReplicationPeerConfigResponse;
321import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.ListReplicationPeersRequest;
322import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.ListReplicationPeersResponse;
323import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.RemoveReplicationPeerRequest;
324import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.RemoveReplicationPeerResponse;
325import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.TransitReplicationPeerSyncReplicationStateRequest;
326import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.TransitReplicationPeerSyncReplicationStateResponse;
327import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.UpdateReplicationPeerConfigRequest;
328import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.UpdateReplicationPeerConfigResponse;
329import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos;
330
331/**
332 * The implementation of AsyncAdmin.
333 * <p>
334 * The word 'Raw' means that this is a low level class. The returned {@link CompletableFuture} will
335 * be finished inside the rpc framework thread, which means that the callbacks registered to the
336 * {@link CompletableFuture} will also be executed inside the rpc framework thread. So users who use
337 * this class should not try to do time consuming tasks in the callbacks.
338 * @since 2.0.0
339 * @see AsyncHBaseAdmin
340 * @see AsyncConnection#getAdmin()
341 * @see AsyncConnection#getAdminBuilder()
342 */
343@InterfaceAudience.Private
344class RawAsyncHBaseAdmin implements AsyncAdmin {
345
346  public static final String FLUSH_TABLE_PROCEDURE_SIGNATURE = "flush-table-proc";
347
348  private static final Logger LOG = LoggerFactory.getLogger(AsyncHBaseAdmin.class);
349
350  private final AsyncConnectionImpl connection;
351
352  private final HashedWheelTimer retryTimer;
353
354  private final AsyncTable<AdvancedScanResultConsumer> metaTable;
355
356  private final long rpcTimeoutNs;
357
358  private final long operationTimeoutNs;
359
360  private final long pauseNs;
361
362  private final long pauseForCQTBENs;
363
364  private final int maxAttempts;
365
366  private final int startLogErrorsCnt;
367
368  private final NonceGenerator ng;
369
370  RawAsyncHBaseAdmin(AsyncConnectionImpl connection, HashedWheelTimer retryTimer,
371      AsyncAdminBuilderBase builder) {
372    this.connection = connection;
373    this.retryTimer = retryTimer;
374    this.metaTable = connection.getTable(META_TABLE_NAME);
375    this.rpcTimeoutNs = builder.rpcTimeoutNs;
376    this.operationTimeoutNs = builder.operationTimeoutNs;
377    this.pauseNs = builder.pauseNs;
378    if (builder.pauseForCQTBENs < builder.pauseNs) {
379      LOG.warn(
380        "Configured value of pauseForCQTBENs is {} ms, which is less than" +
381          " the normal pause value {} ms, use the greater one instead",
382        TimeUnit.NANOSECONDS.toMillis(builder.pauseForCQTBENs),
383        TimeUnit.NANOSECONDS.toMillis(builder.pauseNs));
384      this.pauseForCQTBENs = builder.pauseNs;
385    } else {
386      this.pauseForCQTBENs = builder.pauseForCQTBENs;
387    }
388    this.maxAttempts = builder.maxAttempts;
389    this.startLogErrorsCnt = builder.startLogErrorsCnt;
390    this.ng = connection.getNonceGenerator();
391  }
392
393  <T> MasterRequestCallerBuilder<T> newMasterCaller() {
394    return this.connection.callerFactory.<T> masterRequest()
395      .rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
396      .operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS)
397      .pause(pauseNs, TimeUnit.NANOSECONDS).pauseForCQTBE(pauseForCQTBENs, TimeUnit.NANOSECONDS)
398      .maxAttempts(maxAttempts).startLogErrorsCnt(startLogErrorsCnt);
399  }
400
401  private <T> AdminRequestCallerBuilder<T> newAdminCaller() {
402    return this.connection.callerFactory.<T> adminRequest()
403      .rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
404      .operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS)
405      .pause(pauseNs, TimeUnit.NANOSECONDS).pauseForCQTBE(pauseForCQTBENs, TimeUnit.NANOSECONDS)
406      .maxAttempts(maxAttempts).startLogErrorsCnt(startLogErrorsCnt);
407  }
408
409  @FunctionalInterface
410  private interface MasterRpcCall<RESP, REQ> {
411    void call(MasterService.Interface stub, HBaseRpcController controller, REQ req,
412        RpcCallback<RESP> done);
413  }
414
415  @FunctionalInterface
416  private interface AdminRpcCall<RESP, REQ> {
417    void call(AdminService.Interface stub, HBaseRpcController controller, REQ req,
418        RpcCallback<RESP> done);
419  }
420
421  @FunctionalInterface
422  private interface Converter<D, S> {
423    D convert(S src) throws IOException;
424  }
425
426  private <PREQ, PRESP, RESP> CompletableFuture<RESP> call(HBaseRpcController controller,
427      MasterService.Interface stub, PREQ preq, MasterRpcCall<PRESP, PREQ> rpcCall,
428      Converter<RESP, PRESP> respConverter) {
429    CompletableFuture<RESP> future = new CompletableFuture<>();
430    rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {
431
432      @Override
433      public void run(PRESP resp) {
434        if (controller.failed()) {
435          future.completeExceptionally(controller.getFailed());
436        } else {
437          try {
438            future.complete(respConverter.convert(resp));
439          } catch (IOException e) {
440            future.completeExceptionally(e);
441          }
442        }
443      }
444    });
445    return future;
446  }
447
448  private <PREQ, PRESP, RESP> CompletableFuture<RESP> adminCall(HBaseRpcController controller,
449      AdminService.Interface stub, PREQ preq, AdminRpcCall<PRESP, PREQ> rpcCall,
450      Converter<RESP, PRESP> respConverter) {
451    CompletableFuture<RESP> future = new CompletableFuture<>();
452    rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {
453
454      @Override
455      public void run(PRESP resp) {
456        if (controller.failed()) {
457          future.completeExceptionally(controller.getFailed());
458        } else {
459          try {
460            future.complete(respConverter.convert(resp));
461          } catch (IOException e) {
462            future.completeExceptionally(e);
463          }
464        }
465      }
466    });
467    return future;
468  }
469
470  private <PREQ, PRESP> CompletableFuture<Void> procedureCall(PREQ preq,
471      MasterRpcCall<PRESP, PREQ> rpcCall, Converter<Long, PRESP> respConverter,
472      ProcedureBiConsumer consumer) {
473    return procedureCall(b -> {
474    }, preq, rpcCall, respConverter, consumer);
475  }
476
477  private <PREQ, PRESP> CompletableFuture<Void> procedureCall(TableName tableName, PREQ preq,
478      MasterRpcCall<PRESP, PREQ> rpcCall, Converter<Long, PRESP> respConverter,
479      ProcedureBiConsumer consumer) {
480    return procedureCall(b -> b.priority(tableName), preq, rpcCall, respConverter, consumer);
481  }
482
483  private <PREQ, PRESP> CompletableFuture<Void> procedureCall(
484      Consumer<MasterRequestCallerBuilder<?>> prioritySetter, PREQ preq,
485      MasterRpcCall<PRESP, PREQ> rpcCall, Converter<Long, PRESP> respConverter,
486      ProcedureBiConsumer consumer) {
487    MasterRequestCallerBuilder<Long> builder = this.<Long> newMasterCaller().action((controller,
488        stub) -> this.<PREQ, PRESP, Long> call(controller, stub, preq, rpcCall, respConverter));
489    prioritySetter.accept(builder);
490    CompletableFuture<Long> procFuture = builder.call();
491    CompletableFuture<Void> future = waitProcedureResult(procFuture);
492    addListener(future, consumer);
493    return future;
494  }
495
496  @FunctionalInterface
497  private interface TableOperator {
498    CompletableFuture<Void> operate(TableName table);
499  }
500
501  @Override
502  public CompletableFuture<Boolean> tableExists(TableName tableName) {
503    if (TableName.isMetaTableName(tableName)) {
504      return CompletableFuture.completedFuture(true);
505    }
506    return ClientMetaTableAccessor.tableExists(metaTable, tableName);
507  }
508
509  @Override
510  public CompletableFuture<List<TableDescriptor>> listTableDescriptors(boolean includeSysTables) {
511    return getTableDescriptors(RequestConverter.buildGetTableDescriptorsRequest(null,
512      includeSysTables));
513  }
514
515  /**
516   * {@link #listTableDescriptors(boolean)}
517   */
518  @Override
519  public CompletableFuture<List<TableDescriptor>> listTableDescriptors(Pattern pattern,
520      boolean includeSysTables) {
521    Preconditions.checkNotNull(pattern,
522      "pattern is null. If you don't specify a pattern, "
523          + "use listTableDescriptors(boolean) instead");
524    return getTableDescriptors(RequestConverter.buildGetTableDescriptorsRequest(pattern,
525      includeSysTables));
526  }
527
528  @Override
529  public CompletableFuture<List<TableDescriptor>> listTableDescriptors(List<TableName> tableNames) {
530    Preconditions.checkNotNull(tableNames,
531      "tableNames is null. If you don't specify tableNames, "
532          + "use listTableDescriptors(boolean) instead");
533    if (tableNames.isEmpty()) {
534      return CompletableFuture.completedFuture(Collections.emptyList());
535    }
536    return getTableDescriptors(RequestConverter.buildGetTableDescriptorsRequest(tableNames));
537  }
538
539  private CompletableFuture<List<TableDescriptor>>
540      getTableDescriptors(GetTableDescriptorsRequest request) {
541    return this.<List<TableDescriptor>> newMasterCaller()
542        .action((controller, stub) -> this
543            .<GetTableDescriptorsRequest, GetTableDescriptorsResponse, List<TableDescriptor>> call(
544              controller, stub, request, (s, c, req, done) -> s.getTableDescriptors(c, req, done),
545              (resp) -> ProtobufUtil.toTableDescriptorList(resp)))
546        .call();
547  }
548
549  @Override
550  public CompletableFuture<List<TableName>> listTableNames(boolean includeSysTables) {
551    return getTableNames(RequestConverter.buildGetTableNamesRequest(null, includeSysTables));
552  }
553
554  @Override
555  public CompletableFuture<List<TableName>>
556      listTableNames(Pattern pattern, boolean includeSysTables) {
557    Preconditions.checkNotNull(pattern,
558        "pattern is null. If you don't specify a pattern, use listTableNames(boolean) instead");
559    return getTableNames(RequestConverter.buildGetTableNamesRequest(pattern, includeSysTables));
560  }
561
562  private CompletableFuture<List<TableName>> getTableNames(GetTableNamesRequest request) {
563    return this
564        .<List<TableName>> newMasterCaller()
565        .action(
566          (controller, stub) -> this
567              .<GetTableNamesRequest, GetTableNamesResponse, List<TableName>> call(controller,
568                stub, request, (s, c, req, done) -> s.getTableNames(c, req, done),
569                (resp) -> ProtobufUtil.toTableNameList(resp.getTableNamesList()))).call();
570  }
571
572  @Override
573  public CompletableFuture<List<TableDescriptor>> listTableDescriptorsByNamespace(String name) {
574    return this.<List<TableDescriptor>> newMasterCaller().action((controller, stub) -> this
575        .<ListTableDescriptorsByNamespaceRequest, ListTableDescriptorsByNamespaceResponse,
576        List<TableDescriptor>> call(
577          controller, stub,
578          ListTableDescriptorsByNamespaceRequest.newBuilder().setNamespaceName(name).build(),
579          (s, c, req, done) -> s.listTableDescriptorsByNamespace(c, req, done),
580          (resp) -> ProtobufUtil.toTableDescriptorList(resp)))
581        .call();
582  }
583
584  @Override
585  public CompletableFuture<List<TableName>> listTableNamesByNamespace(String name) {
586    return this.<List<TableName>> newMasterCaller().action((controller, stub) -> this
587        .<ListTableNamesByNamespaceRequest, ListTableNamesByNamespaceResponse,
588        List<TableName>> call(
589          controller, stub,
590          ListTableNamesByNamespaceRequest.newBuilder().setNamespaceName(name).build(),
591          (s, c, req, done) -> s.listTableNamesByNamespace(c, req, done),
592          (resp) -> ProtobufUtil.toTableNameList(resp.getTableNameList())))
593        .call();
594  }
595
596  @Override
597  public CompletableFuture<TableDescriptor> getDescriptor(TableName tableName) {
598    CompletableFuture<TableDescriptor> future = new CompletableFuture<>();
599    addListener(this.<List<TableSchema>> newMasterCaller().priority(tableName)
600      .action((controller, stub) -> this
601        .<GetTableDescriptorsRequest, GetTableDescriptorsResponse, List<TableSchema>> call(
602          controller, stub, RequestConverter.buildGetTableDescriptorsRequest(tableName),
603          (s, c, req, done) -> s.getTableDescriptors(c, req, done),
604          (resp) -> resp.getTableSchemaList()))
605      .call(), (tableSchemas, error) -> {
606        if (error != null) {
607          future.completeExceptionally(error);
608          return;
609        }
610        if (!tableSchemas.isEmpty()) {
611          future.complete(ProtobufUtil.toTableDescriptor(tableSchemas.get(0)));
612        } else {
613          future.completeExceptionally(new TableNotFoundException(tableName.getNameAsString()));
614        }
615      });
616    return future;
617  }
618
619  @Override
620  public CompletableFuture<Void> createTable(TableDescriptor desc) {
621    return createTable(desc.getTableName(),
622      RequestConverter.buildCreateTableRequest(desc, null, ng.getNonceGroup(), ng.newNonce()));
623  }
624
625  @Override
626  public CompletableFuture<Void> createTable(TableDescriptor desc, byte[] startKey, byte[] endKey,
627      int numRegions) {
628    try {
629      return createTable(desc, getSplitKeys(startKey, endKey, numRegions));
630    } catch (IllegalArgumentException e) {
631      return failedFuture(e);
632    }
633  }
634
635  @Override
636  public CompletableFuture<Void> createTable(TableDescriptor desc, byte[][] splitKeys) {
637    Preconditions.checkNotNull(splitKeys, "splitKeys is null. If you don't specify splitKeys,"
638        + " use createTable(TableDescriptor) instead");
639    try {
640      verifySplitKeys(splitKeys);
641      return createTable(desc.getTableName(), RequestConverter.buildCreateTableRequest(desc,
642        splitKeys, ng.getNonceGroup(), ng.newNonce()));
643    } catch (IllegalArgumentException e) {
644      return failedFuture(e);
645    }
646  }
647
648  private CompletableFuture<Void> createTable(TableName tableName, CreateTableRequest request) {
649    Preconditions.checkNotNull(tableName, "table name is null");
650    return this.<CreateTableRequest, CreateTableResponse> procedureCall(tableName, request,
651      (s, c, req, done) -> s.createTable(c, req, done), (resp) -> resp.getProcId(),
652      new CreateTableProcedureBiConsumer(tableName));
653  }
654
655  @Override
656  public CompletableFuture<Void> modifyTable(TableDescriptor desc) {
657    return this.<ModifyTableRequest, ModifyTableResponse> procedureCall(desc.getTableName(),
658      RequestConverter.buildModifyTableRequest(desc.getTableName(), desc, ng.getNonceGroup(),
659        ng.newNonce()), (s, c, req, done) -> s.modifyTable(c, req, done),
660      (resp) -> resp.getProcId(), new ModifyTableProcedureBiConsumer(this, desc.getTableName()));
661  }
662
663  @Override
664  public CompletableFuture<Void> deleteTable(TableName tableName) {
665    return this.<DeleteTableRequest, DeleteTableResponse> procedureCall(tableName,
666      RequestConverter.buildDeleteTableRequest(tableName, ng.getNonceGroup(), ng.newNonce()),
667      (s, c, req, done) -> s.deleteTable(c, req, done), (resp) -> resp.getProcId(),
668      new DeleteTableProcedureBiConsumer(tableName));
669  }
670
671  @Override
672  public CompletableFuture<Void> truncateTable(TableName tableName, boolean preserveSplits) {
673    return this.<TruncateTableRequest, TruncateTableResponse> procedureCall(tableName,
674      RequestConverter.buildTruncateTableRequest(tableName, preserveSplits, ng.getNonceGroup(),
675        ng.newNonce()), (s, c, req, done) -> s.truncateTable(c, req, done),
676      (resp) -> resp.getProcId(), new TruncateTableProcedureBiConsumer(tableName));
677  }
678
679  @Override
680  public CompletableFuture<Void> enableTable(TableName tableName) {
681    return this.<EnableTableRequest, EnableTableResponse> procedureCall(tableName,
682      RequestConverter.buildEnableTableRequest(tableName, ng.getNonceGroup(), ng.newNonce()),
683      (s, c, req, done) -> s.enableTable(c, req, done), (resp) -> resp.getProcId(),
684      new EnableTableProcedureBiConsumer(tableName));
685  }
686
687  @Override
688  public CompletableFuture<Void> disableTable(TableName tableName) {
689    return this.<DisableTableRequest, DisableTableResponse> procedureCall(tableName,
690      RequestConverter.buildDisableTableRequest(tableName, ng.getNonceGroup(), ng.newNonce()),
691      (s, c, req, done) -> s.disableTable(c, req, done), (resp) -> resp.getProcId(),
692      new DisableTableProcedureBiConsumer(tableName));
693  }
694
695  /**
696   * Utility for completing passed TableState {@link CompletableFuture} <code>future</code>
697   * using passed parameters. Sets error or boolean result ('true' if table matches
698   * the passed-in targetState).
699   */
700  private static CompletableFuture<Boolean> completeCheckTableState(
701      CompletableFuture<Boolean> future, TableState tableState, Throwable error,
702      TableState.State targetState, TableName tableName) {
703    if (error != null) {
704      future.completeExceptionally(error);
705    } else {
706      if (tableState != null) {
707        future.complete(tableState.inStates(targetState));
708      } else {
709        future.completeExceptionally(new TableNotFoundException(tableName));
710      }
711    }
712    return future;
713  }
714
715  @Override
716  public CompletableFuture<Boolean> isTableEnabled(TableName tableName) {
717    if (TableName.isMetaTableName(tableName)) {
718      return CompletableFuture.completedFuture(true);
719    }
720    CompletableFuture<Boolean> future = new CompletableFuture<>();
721    addListener(ClientMetaTableAccessor.getTableState(metaTable, tableName),
722      (tableState, error) -> {
723        completeCheckTableState(future, tableState.isPresent() ? tableState.get() : null, error,
724          TableState.State.ENABLED, tableName);
725      });
726    return future;
727  }
728
729  @Override
730  public CompletableFuture<Boolean> isTableDisabled(TableName tableName) {
731    if (TableName.isMetaTableName(tableName)) {
732      return CompletableFuture.completedFuture(false);
733    }
734    CompletableFuture<Boolean> future = new CompletableFuture<>();
735    addListener(ClientMetaTableAccessor.getTableState(metaTable, tableName),
736      (tableState, error) -> {
737        completeCheckTableState(future, tableState.isPresent() ? tableState.get() : null, error,
738          TableState.State.DISABLED, tableName);
739      });
740    return future;
741  }
742
743  @Override
744  public CompletableFuture<Boolean> isTableAvailable(TableName tableName) {
745    if (TableName.isMetaTableName(tableName)) {
746      return connection.registry.getMetaRegionLocations().thenApply(locs -> Stream
747        .of(locs.getRegionLocations()).allMatch(loc -> loc != null && loc.getServerName() != null));
748    }
749    CompletableFuture<Boolean> future = new CompletableFuture<>();
750    addListener(isTableEnabled(tableName), (enabled, error) -> {
751      if (error != null) {
752        if (error instanceof TableNotFoundException) {
753          future.complete(false);
754        } else {
755          future.completeExceptionally(error);
756        }
757        return;
758      }
759      if (!enabled) {
760        future.complete(false);
761      } else {
762        addListener(
763          ClientMetaTableAccessor.getTableHRegionLocations(metaTable, tableName),
764          (locations, error1) -> {
765            if (error1 != null) {
766              future.completeExceptionally(error1);
767              return;
768            }
769            List<HRegionLocation> notDeployedRegions = locations.stream()
770              .filter(loc -> loc.getServerName() == null).collect(Collectors.toList());
771            if (notDeployedRegions.size() > 0) {
772              if (LOG.isDebugEnabled()) {
773                LOG.debug("Table " + tableName + " has " + notDeployedRegions.size() + " regions");
774              }
775              future.complete(false);
776              return;
777            }
778            future.complete(true);
779          });
780      }
781    });
782    return future;
783  }
784
785  @Override
786  public CompletableFuture<Void> addColumnFamily(
787      TableName tableName, ColumnFamilyDescriptor columnFamily) {
788    return this.<AddColumnRequest, AddColumnResponse> procedureCall(tableName,
789      RequestConverter.buildAddColumnRequest(tableName, columnFamily, ng.getNonceGroup(),
790        ng.newNonce()), (s, c, req, done) -> s.addColumn(c, req, done), (resp) -> resp.getProcId(),
791      new AddColumnFamilyProcedureBiConsumer(tableName));
792  }
793
794  @Override
795  public CompletableFuture<Void> deleteColumnFamily(TableName tableName, byte[] columnFamily) {
796    return this.<DeleteColumnRequest, DeleteColumnResponse> procedureCall(tableName,
797      RequestConverter.buildDeleteColumnRequest(tableName, columnFamily, ng.getNonceGroup(),
798        ng.newNonce()), (s, c, req, done) -> s.deleteColumn(c, req, done),
799      (resp) -> resp.getProcId(), new DeleteColumnFamilyProcedureBiConsumer(tableName));
800  }
801
802  @Override
803  public CompletableFuture<Void> modifyColumnFamily(TableName tableName,
804      ColumnFamilyDescriptor columnFamily) {
805    return this.<ModifyColumnRequest, ModifyColumnResponse> procedureCall(tableName,
806      RequestConverter.buildModifyColumnRequest(tableName, columnFamily, ng.getNonceGroup(),
807        ng.newNonce()), (s, c, req, done) -> s.modifyColumn(c, req, done),
808      (resp) -> resp.getProcId(), new ModifyColumnFamilyProcedureBiConsumer(tableName));
809  }
810
811  @Override
812  public CompletableFuture<Void> createNamespace(NamespaceDescriptor descriptor) {
813    return this.<CreateNamespaceRequest, CreateNamespaceResponse> procedureCall(
814      RequestConverter.buildCreateNamespaceRequest(descriptor),
815      (s, c, req, done) -> s.createNamespace(c, req, done), (resp) -> resp.getProcId(),
816      new CreateNamespaceProcedureBiConsumer(descriptor.getName()));
817  }
818
819  @Override
820  public CompletableFuture<Void> modifyNamespace(NamespaceDescriptor descriptor) {
821    return this.<ModifyNamespaceRequest, ModifyNamespaceResponse> procedureCall(
822      RequestConverter.buildModifyNamespaceRequest(descriptor),
823      (s, c, req, done) -> s.modifyNamespace(c, req, done), (resp) -> resp.getProcId(),
824      new ModifyNamespaceProcedureBiConsumer(descriptor.getName()));
825  }
826
827  @Override
828  public CompletableFuture<Void> deleteNamespace(String name) {
829    return this.<DeleteNamespaceRequest, DeleteNamespaceResponse> procedureCall(
830      RequestConverter.buildDeleteNamespaceRequest(name),
831      (s, c, req, done) -> s.deleteNamespace(c, req, done), (resp) -> resp.getProcId(),
832      new DeleteNamespaceProcedureBiConsumer(name));
833  }
834
835  @Override
836  public CompletableFuture<NamespaceDescriptor> getNamespaceDescriptor(String name) {
837    return this
838        .<NamespaceDescriptor> newMasterCaller()
839        .action(
840          (controller, stub) -> this
841              .<GetNamespaceDescriptorRequest, GetNamespaceDescriptorResponse, NamespaceDescriptor>
842                  call(controller, stub, RequestConverter.buildGetNamespaceDescriptorRequest(name),
843                    (s, c, req, done) -> s.getNamespaceDescriptor(c, req, done), (resp)
844                      -> ProtobufUtil.toNamespaceDescriptor(resp.getNamespaceDescriptor()))).call();
845  }
846
847  @Override
848  public CompletableFuture<List<String>> listNamespaces() {
849    return this
850        .<List<String>> newMasterCaller()
851        .action(
852          (controller, stub) -> this
853              .<ListNamespacesRequest, ListNamespacesResponse, List<String>> call(
854                controller, stub, ListNamespacesRequest.newBuilder().build(), (s, c, req,
855                  done) -> s.listNamespaces(c, req, done),
856                (resp) -> resp.getNamespaceNameList())).call();
857  }
858
859  @Override
860  public CompletableFuture<List<NamespaceDescriptor>> listNamespaceDescriptors() {
861    return this
862        .<List<NamespaceDescriptor>> newMasterCaller().action((controller, stub) -> this
863              .<ListNamespaceDescriptorsRequest, ListNamespaceDescriptorsResponse,
864                  List<NamespaceDescriptor>> call(controller, stub,
865                  ListNamespaceDescriptorsRequest.newBuilder().build(), (s, c, req, done) ->
866                      s.listNamespaceDescriptors(c, req, done),
867                    (resp) -> ProtobufUtil.toNamespaceDescriptorList(resp))).call();
868  }
869
870  @Override
871  public CompletableFuture<List<RegionInfo>> getRegions(ServerName serverName) {
872    return this.<List<RegionInfo>> newAdminCaller()
873        .action((controller, stub) -> this
874            .<GetOnlineRegionRequest, GetOnlineRegionResponse, List<RegionInfo>> adminCall(
875              controller, stub, RequestConverter.buildGetOnlineRegionRequest(),
876              (s, c, req, done) -> s.getOnlineRegion(c, req, done),
877              resp -> ProtobufUtil.getRegionInfos(resp)))
878        .serverName(serverName).call();
879  }
880
881  @Override
882  public CompletableFuture<List<RegionInfo>> getRegions(TableName tableName) {
883    if (tableName.equals(META_TABLE_NAME)) {
884      return connection.registry.getMetaRegionLocations()
885        .thenApply(locs -> Stream.of(locs.getRegionLocations()).map(HRegionLocation::getRegion)
886          .collect(Collectors.toList()));
887    } else {
888      return ClientMetaTableAccessor.getTableHRegionLocations(metaTable, tableName)
889        .thenApply(
890          locs -> locs.stream().map(HRegionLocation::getRegion).collect(Collectors.toList()));
891    }
892  }
893  @Override
894  public CompletableFuture<Void> flush(TableName tableName) {
895    return flush(tableName, null);
896  }
897
898  @Override
899  public CompletableFuture<Void> flush(TableName tableName, byte[] columnFamily) {
900    CompletableFuture<Void> future = new CompletableFuture<>();
901    addListener(tableExists(tableName), (exists, err) -> {
902      if (err != null) {
903        future.completeExceptionally(err);
904      } else if (!exists) {
905        future.completeExceptionally(new TableNotFoundException(tableName));
906      } else {
907        addListener(isTableEnabled(tableName), (tableEnabled, err2) -> {
908          if (err2 != null) {
909            future.completeExceptionally(err2);
910          } else if (!tableEnabled) {
911            future.completeExceptionally(new TableNotEnabledException(tableName));
912          } else {
913            Map<String, String> props = new HashMap<>();
914            if (columnFamily != null) {
915              props.put(HConstants.FAMILY_KEY_STR, Bytes.toString(columnFamily));
916            }
917            addListener(execProcedure(FLUSH_TABLE_PROCEDURE_SIGNATURE, tableName.getNameAsString(),
918              props), (ret, err3) -> {
919                if (err3 != null) {
920                  future.completeExceptionally(err3);
921                } else {
922                  future.complete(ret);
923                }
924              });
925          }
926        });
927      }
928    });
929    return future;
930  }
931
932  @Override
933  public CompletableFuture<Void> flushRegion(byte[] regionName) {
934    return flushRegionInternal(regionName, null, false).thenAccept(r -> {
935    });
936  }
937
938  @Override
939  public CompletableFuture<Void> flushRegion(byte[] regionName, byte[] columnFamily) {
940    Preconditions.checkNotNull(columnFamily, "columnFamily is null."
941      + "If you don't specify a columnFamily, use flushRegion(regionName) instead");
942    return flushRegionInternal(regionName, columnFamily, false)
943      .thenAccept(r -> {});
944  }
945
946  /**
947   * This method is for internal use only, where we need the response of the flush.
948   * <p/>
949   * As it exposes the protobuf message, please do <strong>NOT</strong> try to expose it as a public
950   * API.
951   */
952  CompletableFuture<FlushRegionResponse> flushRegionInternal(byte[] regionName,
953    byte[] columnFamily, boolean writeFlushWALMarker) {
954    CompletableFuture<FlushRegionResponse> future = new CompletableFuture<>();
955    addListener(getRegionLocation(regionName), (location, err) -> {
956      if (err != null) {
957        future.completeExceptionally(err);
958        return;
959      }
960      ServerName serverName = location.getServerName();
961      if (serverName == null) {
962        future
963          .completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
964        return;
965      }
966      addListener(
967        flush(serverName, location.getRegion(), columnFamily, writeFlushWALMarker),
968        (ret, err2) -> {
969          if (err2 != null) {
970            future.completeExceptionally(err2);
971          } else {
972            future.complete(ret);
973          }});
974    });
975    return future;
976  }
977
978  private CompletableFuture<FlushRegionResponse> flush(ServerName serverName, RegionInfo regionInfo,
979    byte[] columnFamily, boolean writeFlushWALMarker) {
980    return this.<FlushRegionResponse> newAdminCaller().serverName(serverName)
981      .action((controller, stub) -> this
982        .<FlushRegionRequest, FlushRegionResponse, FlushRegionResponse> adminCall(controller, stub,
983          RequestConverter.buildFlushRegionRequest(regionInfo.getRegionName(),
984            columnFamily, writeFlushWALMarker),
985          (s, c, req, done) -> s.flushRegion(c, req, done), resp -> resp))
986      .call();
987  }
988
989  @Override
990  public CompletableFuture<Void> flushRegionServer(ServerName sn) {
991    CompletableFuture<Void> future = new CompletableFuture<>();
992    addListener(getRegions(sn), (hRegionInfos, err) -> {
993      if (err != null) {
994        future.completeExceptionally(err);
995        return;
996      }
997      List<CompletableFuture<Void>> compactFutures = new ArrayList<>();
998      if (hRegionInfos != null) {
999        hRegionInfos.forEach(
1000          region -> compactFutures.add(
1001            flush(sn, region, null, false).thenAccept(r -> {})
1002          )
1003        );
1004      }
1005      addListener(CompletableFuture.allOf(
1006        compactFutures.toArray(new CompletableFuture<?>[compactFutures.size()])), (ret, err2) -> {
1007          if (err2 != null) {
1008            future.completeExceptionally(err2);
1009          } else {
1010            future.complete(ret);
1011          }
1012        });
1013    });
1014    return future;
1015  }
1016
1017  @Override
1018  public CompletableFuture<Void> compact(TableName tableName, CompactType compactType) {
1019    return compact(tableName, null, false, compactType);
1020  }
1021
1022  @Override
1023  public CompletableFuture<Void> compact(TableName tableName, byte[] columnFamily,
1024      CompactType compactType) {
1025    Preconditions.checkNotNull(columnFamily, "columnFamily is null. "
1026        + "If you don't specify a columnFamily, use compact(TableName) instead");
1027    return compact(tableName, columnFamily, false, compactType);
1028  }
1029
1030  @Override
1031  public CompletableFuture<Void> compactRegion(byte[] regionName) {
1032    return compactRegion(regionName, null, false);
1033  }
1034
1035  @Override
1036  public CompletableFuture<Void> compactRegion(byte[] regionName, byte[] columnFamily) {
1037    Preconditions.checkNotNull(columnFamily, "columnFamily is null."
1038        + " If you don't specify a columnFamily, use compactRegion(regionName) instead");
1039    return compactRegion(regionName, columnFamily, false);
1040  }
1041
1042  @Override
1043  public CompletableFuture<Void> majorCompact(TableName tableName, CompactType compactType) {
1044    return compact(tableName, null, true, compactType);
1045  }
1046
1047  @Override
1048  public CompletableFuture<Void> majorCompact(TableName tableName, byte[] columnFamily,
1049      CompactType compactType) {
1050    Preconditions.checkNotNull(columnFamily, "columnFamily is null."
1051        + "If you don't specify a columnFamily, use compact(TableName) instead");
1052    return compact(tableName, columnFamily, true, compactType);
1053  }
1054
1055  @Override
1056  public CompletableFuture<Void> majorCompactRegion(byte[] regionName) {
1057    return compactRegion(regionName, null, true);
1058  }
1059
1060  @Override
1061  public CompletableFuture<Void> majorCompactRegion(byte[] regionName, byte[] columnFamily) {
1062    Preconditions.checkNotNull(columnFamily, "columnFamily is null."
1063        + " If you don't specify a columnFamily, use majorCompactRegion(regionName) instead");
1064    return compactRegion(regionName, columnFamily, true);
1065  }
1066
1067  @Override
1068  public CompletableFuture<Void> compactRegionServer(ServerName sn) {
1069    return compactRegionServer(sn, false);
1070  }
1071
1072  @Override
1073  public CompletableFuture<Void> majorCompactRegionServer(ServerName sn) {
1074    return compactRegionServer(sn, true);
1075  }
1076
1077  private CompletableFuture<Void> compactRegionServer(ServerName sn, boolean major) {
1078    CompletableFuture<Void> future = new CompletableFuture<>();
1079    addListener(getRegions(sn), (hRegionInfos, err) -> {
1080      if (err != null) {
1081        future.completeExceptionally(err);
1082        return;
1083      }
1084      List<CompletableFuture<Void>> compactFutures = new ArrayList<>();
1085      if (hRegionInfos != null) {
1086        hRegionInfos.forEach(region -> compactFutures.add(compact(sn, region, major, null)));
1087      }
1088      addListener(CompletableFuture.allOf(
1089        compactFutures.toArray(new CompletableFuture<?>[compactFutures.size()])), (ret, err2) -> {
1090          if (err2 != null) {
1091            future.completeExceptionally(err2);
1092          } else {
1093            future.complete(ret);
1094          }
1095        });
1096    });
1097    return future;
1098  }
1099
1100  private CompletableFuture<Void> compactRegion(byte[] regionName, byte[] columnFamily,
1101      boolean major) {
1102    CompletableFuture<Void> future = new CompletableFuture<>();
1103    addListener(getRegionLocation(regionName), (location, err) -> {
1104      if (err != null) {
1105        future.completeExceptionally(err);
1106        return;
1107      }
1108      ServerName serverName = location.getServerName();
1109      if (serverName == null) {
1110        future
1111          .completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
1112        return;
1113      }
1114      addListener(compact(location.getServerName(), location.getRegion(), major, columnFamily),
1115        (ret, err2) -> {
1116          if (err2 != null) {
1117            future.completeExceptionally(err2);
1118          } else {
1119            future.complete(ret);
1120          }
1121        });
1122    });
1123    return future;
1124  }
1125
1126  /**
1127   * List all region locations for the specific table.
1128   */
1129  private CompletableFuture<List<HRegionLocation>> getTableHRegionLocations(TableName tableName) {
1130    if (TableName.META_TABLE_NAME.equals(tableName)) {
1131      CompletableFuture<List<HRegionLocation>> future = new CompletableFuture<>();
1132      addListener(connection.registry.getMetaRegionLocations(), (metaRegions, err) -> {
1133        if (err != null) {
1134          future.completeExceptionally(err);
1135        } else if (metaRegions == null || metaRegions.isEmpty() ||
1136          metaRegions.getDefaultRegionLocation() == null) {
1137          future.completeExceptionally(new IOException("meta region does not found"));
1138        } else {
1139          future.complete(Collections.singletonList(metaRegions.getDefaultRegionLocation()));
1140        }
1141      });
1142      return future;
1143    } else {
1144      // For non-meta table, we fetch all locations by scanning hbase:meta table
1145      return ClientMetaTableAccessor.getTableHRegionLocations(metaTable, tableName);
1146    }
1147  }
1148
1149  /**
1150   * Compact column family of a table, Asynchronous operation even if CompletableFuture.get()
1151   */
1152  private CompletableFuture<Void> compact(TableName tableName, byte[] columnFamily, boolean major,
1153      CompactType compactType) {
1154    CompletableFuture<Void> future = new CompletableFuture<>();
1155
1156    switch (compactType) {
1157      case MOB:
1158        addListener(connection.registry.getActiveMaster(), (serverName, err) -> {
1159          if (err != null) {
1160            future.completeExceptionally(err);
1161            return;
1162          }
1163          RegionInfo regionInfo = RegionInfo.createMobRegionInfo(tableName);
1164          addListener(compact(serverName, regionInfo, major, columnFamily), (ret, err2) -> {
1165            if (err2 != null) {
1166              future.completeExceptionally(err2);
1167            } else {
1168              future.complete(ret);
1169            }
1170          });
1171        });
1172        break;
1173      case NORMAL:
1174        addListener(getTableHRegionLocations(tableName), (locations, err) -> {
1175          if (err != null) {
1176            future.completeExceptionally(err);
1177            return;
1178          }
1179          if (locations == null || locations.isEmpty()) {
1180            future.completeExceptionally(new TableNotFoundException(tableName));
1181          }
1182          CompletableFuture<?>[] compactFutures =
1183            locations.stream().filter(l -> l.getRegion() != null)
1184              .filter(l -> !l.getRegion().isOffline()).filter(l -> l.getServerName() != null)
1185              .map(l -> compact(l.getServerName(), l.getRegion(), major, columnFamily))
1186              .toArray(CompletableFuture<?>[]::new);
1187          // future complete unless all of the compact futures are completed.
1188          addListener(CompletableFuture.allOf(compactFutures), (ret, err2) -> {
1189            if (err2 != null) {
1190              future.completeExceptionally(err2);
1191            } else {
1192              future.complete(ret);
1193            }
1194          });
1195        });
1196        break;
1197      default:
1198        throw new IllegalArgumentException("Unknown compactType: " + compactType);
1199    }
1200    return future;
1201  }
1202
1203  /**
1204   * Compact the region at specific region server.
1205   */
1206  private CompletableFuture<Void> compact(final ServerName sn, final RegionInfo hri,
1207      final boolean major, byte[] columnFamily) {
1208    return this
1209        .<Void> newAdminCaller()
1210        .serverName(sn)
1211        .action(
1212          (controller, stub) -> this.<CompactRegionRequest, CompactRegionResponse, Void> adminCall(
1213            controller, stub, RequestConverter.buildCompactRegionRequest(hri.getRegionName(),
1214              major, columnFamily), (s, c, req, done) -> s.compactRegion(c, req, done),
1215            resp -> null)).call();
1216  }
1217
1218  private byte[] toEncodeRegionName(byte[] regionName) {
1219    return RegionInfo.isEncodedRegionName(regionName) ? regionName :
1220      Bytes.toBytes(RegionInfo.encodeRegionName(regionName));
1221  }
1222
1223  private void checkAndGetTableName(byte[] encodeRegionName, AtomicReference<TableName> tableName,
1224      CompletableFuture<TableName> result) {
1225    addListener(getRegionLocation(encodeRegionName), (location, err) -> {
1226      if (err != null) {
1227        result.completeExceptionally(err);
1228        return;
1229      }
1230      RegionInfo regionInfo = location.getRegion();
1231      if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
1232        result.completeExceptionally(
1233          new IllegalArgumentException("Can't invoke merge on non-default regions directly"));
1234        return;
1235      }
1236      if (!tableName.compareAndSet(null, regionInfo.getTable())) {
1237        if (!tableName.get().equals(regionInfo.getTable())) {
1238          // tables of this two region should be same.
1239          result.completeExceptionally(
1240            new IllegalArgumentException("Cannot merge regions from two different tables " +
1241              tableName.get() + " and " + regionInfo.getTable()));
1242        } else {
1243          result.complete(tableName.get());
1244        }
1245      }
1246    });
1247  }
1248
1249  private CompletableFuture<TableName> checkRegionsAndGetTableName(byte[][] encodedRegionNames) {
1250    AtomicReference<TableName> tableNameRef = new AtomicReference<>();
1251    CompletableFuture<TableName> future = new CompletableFuture<>();
1252    for (byte[] encodedRegionName : encodedRegionNames) {
1253      checkAndGetTableName(encodedRegionName, tableNameRef, future);
1254    }
1255    return future;
1256  }
1257
1258  @Override
1259  public CompletableFuture<Boolean> mergeSwitch(boolean enabled, boolean drainMerges) {
1260    return setSplitOrMergeOn(enabled, drainMerges, MasterSwitchType.MERGE);
1261  }
1262
1263  @Override
1264  public CompletableFuture<Boolean> isMergeEnabled() {
1265    return isSplitOrMergeOn(MasterSwitchType.MERGE);
1266  }
1267
1268  @Override
1269  public CompletableFuture<Boolean> splitSwitch(boolean enabled, boolean drainSplits) {
1270    return setSplitOrMergeOn(enabled, drainSplits, MasterSwitchType.SPLIT);
1271  }
1272
1273  @Override
1274  public CompletableFuture<Boolean> isSplitEnabled() {
1275    return isSplitOrMergeOn(MasterSwitchType.SPLIT);
1276  }
1277
1278  private CompletableFuture<Boolean> setSplitOrMergeOn(boolean enabled, boolean synchronous,
1279      MasterSwitchType switchType) {
1280    SetSplitOrMergeEnabledRequest request =
1281      RequestConverter.buildSetSplitOrMergeEnabledRequest(enabled, synchronous, switchType);
1282    return this.<Boolean> newMasterCaller()
1283      .action((controller, stub) -> this
1284        .<SetSplitOrMergeEnabledRequest, SetSplitOrMergeEnabledResponse, Boolean> call(controller,
1285          stub, request, (s, c, req, done) -> s.setSplitOrMergeEnabled(c, req, done),
1286          (resp) -> resp.getPrevValueList().get(0)))
1287      .call();
1288  }
1289
1290  private CompletableFuture<Boolean> isSplitOrMergeOn(MasterSwitchType switchType) {
1291    IsSplitOrMergeEnabledRequest request =
1292        RequestConverter.buildIsSplitOrMergeEnabledRequest(switchType);
1293    return this
1294        .<Boolean> newMasterCaller()
1295        .action(
1296          (controller, stub) -> this
1297              .<IsSplitOrMergeEnabledRequest, IsSplitOrMergeEnabledResponse, Boolean> call(
1298                controller, stub, request,
1299                (s, c, req, done) -> s.isSplitOrMergeEnabled(c, req, done),
1300                (resp) -> resp.getEnabled())).call();
1301  }
1302
1303  @Override
1304  public CompletableFuture<Void> mergeRegions(List<byte[]> nameOfRegionsToMerge, boolean forcible) {
1305    if (nameOfRegionsToMerge.size() < 2) {
1306      return failedFuture(new IllegalArgumentException(
1307        "Can not merge only " + nameOfRegionsToMerge.size() + " region"));
1308    }
1309    CompletableFuture<Void> future = new CompletableFuture<>();
1310    byte[][] encodedNameOfRegionsToMerge =
1311      nameOfRegionsToMerge.stream().map(this::toEncodeRegionName).toArray(byte[][]::new);
1312
1313    addListener(checkRegionsAndGetTableName(encodedNameOfRegionsToMerge), (tableName, err) -> {
1314      if (err != null) {
1315        future.completeExceptionally(err);
1316        return;
1317      }
1318
1319      final MergeTableRegionsRequest request;
1320      try {
1321        request = RequestConverter.buildMergeTableRegionsRequest(encodedNameOfRegionsToMerge,
1322          forcible, ng.getNonceGroup(), ng.newNonce());
1323      } catch (DeserializationException e) {
1324        future.completeExceptionally(e);
1325        return;
1326      }
1327
1328      addListener(
1329        this.procedureCall(tableName, request,
1330          MasterService.Interface::mergeTableRegions, MergeTableRegionsResponse::getProcId,
1331          new MergeTableRegionProcedureBiConsumer(tableName)),
1332        (ret, err2) -> {
1333          if (err2 != null) {
1334            future.completeExceptionally(err2);
1335          } else {
1336            future.complete(ret);
1337          }
1338        });
1339    });
1340    return future;
1341  }
1342
1343  @Override
1344  public CompletableFuture<Void> split(TableName tableName) {
1345    CompletableFuture<Void> future = new CompletableFuture<>();
1346    addListener(tableExists(tableName), (exist, error) -> {
1347      if (error != null) {
1348        future.completeExceptionally(error);
1349        return;
1350      }
1351      if (!exist) {
1352        future.completeExceptionally(new TableNotFoundException(tableName));
1353        return;
1354      }
1355      addListener(metaTable
1356        .scanAll(new Scan().setReadType(ReadType.PREAD).addFamily(HConstants.CATALOG_FAMILY)
1357          .withStartRow(ClientMetaTableAccessor.getTableStartRowForMeta(tableName,
1358            ClientMetaTableAccessor.QueryType.REGION))
1359          .withStopRow(ClientMetaTableAccessor.getTableStopRowForMeta(tableName,
1360            ClientMetaTableAccessor.QueryType.REGION))),
1361        (results, err2) -> {
1362          if (err2 != null) {
1363            future.completeExceptionally(err2);
1364            return;
1365          }
1366          if (results != null && !results.isEmpty()) {
1367            List<CompletableFuture<Void>> splitFutures = new ArrayList<>();
1368            for (Result r : results) {
1369              if (r.isEmpty() || CatalogFamilyFormat.getRegionInfo(r) == null) {
1370                continue;
1371              }
1372              RegionLocations rl = CatalogFamilyFormat.getRegionLocations(r);
1373              if (rl != null) {
1374                for (HRegionLocation h : rl.getRegionLocations()) {
1375                  if (h != null && h.getServerName() != null) {
1376                    RegionInfo hri = h.getRegion();
1377                    if (hri == null || hri.isSplitParent() ||
1378                      hri.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
1379                      continue;
1380                    }
1381                    splitFutures.add(split(hri, null));
1382                  }
1383                }
1384              }
1385            }
1386            addListener(
1387              CompletableFuture
1388                .allOf(splitFutures.toArray(new CompletableFuture<?>[splitFutures.size()])),
1389              (ret, exception) -> {
1390                if (exception != null) {
1391                  future.completeExceptionally(exception);
1392                  return;
1393                }
1394                future.complete(ret);
1395              });
1396          } else {
1397            future.complete(null);
1398          }
1399        });
1400    });
1401    return future;
1402  }
1403
1404  @Override
1405  public CompletableFuture<Void> split(TableName tableName, byte[] splitPoint) {
1406    CompletableFuture<Void> result = new CompletableFuture<>();
1407    if (splitPoint == null) {
1408      return failedFuture(new IllegalArgumentException("splitPoint can not be null."));
1409    }
1410    addListener(connection.getRegionLocator(tableName).getRegionLocation(splitPoint, true),
1411      (loc, err) -> {
1412        if (err != null) {
1413          result.completeExceptionally(err);
1414        } else if (loc == null || loc.getRegion() == null) {
1415          result.completeExceptionally(new IllegalArgumentException(
1416            "Region does not found: rowKey=" + Bytes.toStringBinary(splitPoint)));
1417        } else {
1418          addListener(splitRegion(loc.getRegion().getRegionName(), splitPoint), (ret, err2) -> {
1419            if (err2 != null) {
1420              result.completeExceptionally(err2);
1421            } else {
1422              result.complete(ret);
1423            }
1424
1425          });
1426        }
1427      });
1428    return result;
1429  }
1430
1431  @Override
1432  public CompletableFuture<Void> splitRegion(byte[] regionName) {
1433    CompletableFuture<Void> future = new CompletableFuture<>();
1434    addListener(getRegionLocation(regionName), (location, err) -> {
1435      if (err != null) {
1436        future.completeExceptionally(err);
1437        return;
1438      }
1439      RegionInfo regionInfo = location.getRegion();
1440      if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
1441        future
1442          .completeExceptionally(new IllegalArgumentException("Can't split replicas directly. " +
1443            "Replicas are auto-split when their primary is split."));
1444        return;
1445      }
1446      ServerName serverName = location.getServerName();
1447      if (serverName == null) {
1448        future
1449          .completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
1450        return;
1451      }
1452      addListener(split(regionInfo, null), (ret, err2) -> {
1453        if (err2 != null) {
1454          future.completeExceptionally(err2);
1455        } else {
1456          future.complete(ret);
1457        }
1458      });
1459    });
1460    return future;
1461  }
1462
1463  @Override
1464  public CompletableFuture<Void> splitRegion(byte[] regionName, byte[] splitPoint) {
1465    Preconditions.checkNotNull(splitPoint,
1466      "splitPoint is null. If you don't specify a splitPoint, use splitRegion(byte[]) instead");
1467    CompletableFuture<Void> future = new CompletableFuture<>();
1468    addListener(getRegionLocation(regionName), (location, err) -> {
1469      if (err != null) {
1470        future.completeExceptionally(err);
1471        return;
1472      }
1473      RegionInfo regionInfo = location.getRegion();
1474      if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
1475        future
1476          .completeExceptionally(new IllegalArgumentException("Can't split replicas directly. " +
1477            "Replicas are auto-split when their primary is split."));
1478        return;
1479      }
1480      ServerName serverName = location.getServerName();
1481      if (serverName == null) {
1482        future
1483          .completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
1484        return;
1485      }
1486      if (regionInfo.getStartKey() != null &&
1487        Bytes.compareTo(regionInfo.getStartKey(), splitPoint) == 0) {
1488        future.completeExceptionally(
1489          new IllegalArgumentException("should not give a splitkey which equals to startkey!"));
1490        return;
1491      }
1492      addListener(split(regionInfo, splitPoint), (ret, err2) -> {
1493        if (err2 != null) {
1494          future.completeExceptionally(err2);
1495        } else {
1496          future.complete(ret);
1497        }
1498      });
1499    });
1500    return future;
1501  }
1502
1503  private CompletableFuture<Void> split(final RegionInfo hri, byte[] splitPoint) {
1504    CompletableFuture<Void> future = new CompletableFuture<>();
1505    TableName tableName = hri.getTable();
1506    final SplitTableRegionRequest request;
1507    try {
1508      request = RequestConverter.buildSplitTableRegionRequest(hri, splitPoint, ng.getNonceGroup(),
1509        ng.newNonce());
1510    } catch (DeserializationException e) {
1511      future.completeExceptionally(e);
1512      return future;
1513    }
1514
1515    addListener(
1516      this.procedureCall(tableName,
1517        request, MasterService.Interface::splitRegion, SplitTableRegionResponse::getProcId,
1518        new SplitTableRegionProcedureBiConsumer(tableName)),
1519      (ret, err2) -> {
1520        if (err2 != null) {
1521          future.completeExceptionally(err2);
1522        } else {
1523          future.complete(ret);
1524        }
1525      });
1526    return future;
1527  }
1528
1529  @Override
1530  public CompletableFuture<Void> assign(byte[] regionName) {
1531    CompletableFuture<Void> future = new CompletableFuture<>();
1532    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
1533      if (err != null) {
1534        future.completeExceptionally(err);
1535        return;
1536      }
1537      addListener(this.<Void> newMasterCaller().priority(regionInfo.getTable())
1538        .action(((controller, stub) -> this.<AssignRegionRequest, AssignRegionResponse, Void> call(
1539          controller, stub, RequestConverter.buildAssignRegionRequest(regionInfo.getRegionName()),
1540          (s, c, req, done) -> s.assignRegion(c, req, done), resp -> null)))
1541        .call(), (ret, err2) -> {
1542          if (err2 != null) {
1543            future.completeExceptionally(err2);
1544          } else {
1545            future.complete(ret);
1546          }
1547        });
1548    });
1549    return future;
1550  }
1551
1552  @Override
1553  public CompletableFuture<Void> unassign(byte[] regionName) {
1554    CompletableFuture<Void> future = new CompletableFuture<>();
1555    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
1556      if (err != null) {
1557        future.completeExceptionally(err);
1558        return;
1559      }
1560      addListener(
1561        this.<Void> newMasterCaller().priority(regionInfo.getTable())
1562          .action(((controller, stub) -> this
1563            .<UnassignRegionRequest, UnassignRegionResponse, Void> call(controller, stub,
1564              RequestConverter.buildUnassignRegionRequest(regionInfo.getRegionName()),
1565              (s, c, req, done) -> s.unassignRegion(c, req, done), resp -> null)))
1566          .call(),
1567        (ret, err2) -> {
1568          if (err2 != null) {
1569            future.completeExceptionally(err2);
1570          } else {
1571            future.complete(ret);
1572          }
1573        });
1574    });
1575    return future;
1576  }
1577
1578  @Override
1579  public CompletableFuture<Void> offline(byte[] regionName) {
1580    CompletableFuture<Void> future = new CompletableFuture<>();
1581    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
1582      if (err != null) {
1583        future.completeExceptionally(err);
1584        return;
1585      }
1586      addListener(
1587        this.<Void> newMasterCaller().priority(regionInfo.getTable())
1588          .action(((controller, stub) -> this
1589            .<OfflineRegionRequest, OfflineRegionResponse, Void> call(controller, stub,
1590              RequestConverter.buildOfflineRegionRequest(regionInfo.getRegionName()),
1591              (s, c, req, done) -> s.offlineRegion(c, req, done), resp -> null)))
1592          .call(),
1593        (ret, err2) -> {
1594          if (err2 != null) {
1595            future.completeExceptionally(err2);
1596          } else {
1597            future.complete(ret);
1598          }
1599        });
1600    });
1601    return future;
1602  }
1603
1604  @Override
1605  public CompletableFuture<Void> move(byte[] regionName) {
1606    CompletableFuture<Void> future = new CompletableFuture<>();
1607    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
1608      if (err != null) {
1609        future.completeExceptionally(err);
1610        return;
1611      }
1612      addListener(
1613        moveRegion(regionInfo,
1614          RequestConverter.buildMoveRegionRequest(regionInfo.getEncodedNameAsBytes(), null)),
1615        (ret, err2) -> {
1616          if (err2 != null) {
1617            future.completeExceptionally(err2);
1618          } else {
1619            future.complete(ret);
1620          }
1621        });
1622    });
1623    return future;
1624  }
1625
1626  @Override
1627  public CompletableFuture<Void> move(byte[] regionName, ServerName destServerName) {
1628    Preconditions.checkNotNull(destServerName,
1629      "destServerName is null. If you don't specify a destServerName, use move(byte[]) instead");
1630    CompletableFuture<Void> future = new CompletableFuture<>();
1631    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
1632      if (err != null) {
1633        future.completeExceptionally(err);
1634        return;
1635      }
1636      addListener(
1637        moveRegion(regionInfo, RequestConverter
1638          .buildMoveRegionRequest(regionInfo.getEncodedNameAsBytes(), destServerName)),
1639        (ret, err2) -> {
1640          if (err2 != null) {
1641            future.completeExceptionally(err2);
1642          } else {
1643            future.complete(ret);
1644          }
1645        });
1646    });
1647    return future;
1648  }
1649
1650  private CompletableFuture<Void> moveRegion(RegionInfo regionInfo, MoveRegionRequest request) {
1651    return this.<Void> newMasterCaller().priority(regionInfo.getTable())
1652      .action(
1653        (controller, stub) -> this.<MoveRegionRequest, MoveRegionResponse, Void> call(controller,
1654          stub, request, (s, c, req, done) -> s.moveRegion(c, req, done), resp -> null))
1655      .call();
1656  }
1657
1658  @Override
1659  public CompletableFuture<Void> setQuota(QuotaSettings quota) {
1660    return this
1661        .<Void> newMasterCaller()
1662        .action(
1663          (controller, stub) -> this.<SetQuotaRequest, SetQuotaResponse, Void> call(controller,
1664            stub, QuotaSettings.buildSetQuotaRequestProto(quota),
1665            (s, c, req, done) -> s.setQuota(c, req, done), (resp) -> null)).call();
1666  }
1667
1668  @Override
1669  public CompletableFuture<List<QuotaSettings>> getQuota(QuotaFilter filter) {
1670    CompletableFuture<List<QuotaSettings>> future = new CompletableFuture<>();
1671    Scan scan = QuotaTableUtil.makeScan(filter);
1672    this.connection.getTableBuilder(QuotaTableUtil.QUOTA_TABLE_NAME).build()
1673        .scan(scan, new AdvancedScanResultConsumer() {
1674          List<QuotaSettings> settings = new ArrayList<>();
1675
1676          @Override
1677          public void onNext(Result[] results, ScanController controller) {
1678            for (Result result : results) {
1679              try {
1680                QuotaTableUtil.parseResultToCollection(result, settings);
1681              } catch (IOException e) {
1682                controller.terminate();
1683                future.completeExceptionally(e);
1684              }
1685            }
1686          }
1687
1688          @Override
1689          public void onError(Throwable error) {
1690            future.completeExceptionally(error);
1691          }
1692
1693          @Override
1694          public void onComplete() {
1695            future.complete(settings);
1696          }
1697        });
1698    return future;
1699  }
1700
1701  @Override
1702  public CompletableFuture<Void> addReplicationPeer(String peerId,
1703      ReplicationPeerConfig peerConfig, boolean enabled) {
1704    return this.<AddReplicationPeerRequest, AddReplicationPeerResponse> procedureCall(
1705      RequestConverter.buildAddReplicationPeerRequest(peerId, peerConfig, enabled),
1706      (s, c, req, done) -> s.addReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
1707      new ReplicationProcedureBiConsumer(peerId, () -> "ADD_REPLICATION_PEER"));
1708  }
1709
1710  @Override
1711  public CompletableFuture<Void> removeReplicationPeer(String peerId) {
1712    return this.<RemoveReplicationPeerRequest, RemoveReplicationPeerResponse> procedureCall(
1713      RequestConverter.buildRemoveReplicationPeerRequest(peerId),
1714      (s, c, req, done) -> s.removeReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
1715      new ReplicationProcedureBiConsumer(peerId, () -> "REMOVE_REPLICATION_PEER"));
1716  }
1717
1718  @Override
1719  public CompletableFuture<Void> enableReplicationPeer(String peerId) {
1720    return this.<EnableReplicationPeerRequest, EnableReplicationPeerResponse> procedureCall(
1721      RequestConverter.buildEnableReplicationPeerRequest(peerId),
1722      (s, c, req, done) -> s.enableReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
1723      new ReplicationProcedureBiConsumer(peerId, () -> "ENABLE_REPLICATION_PEER"));
1724  }
1725
1726  @Override
1727  public CompletableFuture<Void> disableReplicationPeer(String peerId) {
1728    return this.<DisableReplicationPeerRequest, DisableReplicationPeerResponse> procedureCall(
1729      RequestConverter.buildDisableReplicationPeerRequest(peerId),
1730      (s, c, req, done) -> s.disableReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
1731      new ReplicationProcedureBiConsumer(peerId, () -> "DISABLE_REPLICATION_PEER"));
1732  }
1733
1734  @Override
1735  public CompletableFuture<ReplicationPeerConfig> getReplicationPeerConfig(String peerId) {
1736    return this.<ReplicationPeerConfig> newMasterCaller().action((controller, stub) -> this
1737      .<GetReplicationPeerConfigRequest, GetReplicationPeerConfigResponse, ReplicationPeerConfig>
1738          call(controller, stub, RequestConverter.buildGetReplicationPeerConfigRequest(peerId),
1739            (s, c, req, done) -> s.getReplicationPeerConfig(c, req, done),
1740            (resp) -> ReplicationPeerConfigUtil.convert(resp.getPeerConfig()))).call();
1741  }
1742
1743  @Override
1744  public CompletableFuture<Void> updateReplicationPeerConfig(String peerId,
1745      ReplicationPeerConfig peerConfig) {
1746    return this
1747      .<UpdateReplicationPeerConfigRequest, UpdateReplicationPeerConfigResponse> procedureCall(
1748        RequestConverter.buildUpdateReplicationPeerConfigRequest(peerId, peerConfig),
1749        (s, c, req, done) -> s.updateReplicationPeerConfig(c, req, done),
1750        (resp) -> resp.getProcId(),
1751        new ReplicationProcedureBiConsumer(peerId, () -> "UPDATE_REPLICATION_PEER_CONFIG"));
1752  }
1753
1754  @Override
1755  public CompletableFuture<Void> transitReplicationPeerSyncReplicationState(String peerId,
1756      SyncReplicationState clusterState) {
1757    return this.<TransitReplicationPeerSyncReplicationStateRequest,
1758        TransitReplicationPeerSyncReplicationStateResponse> procedureCall(
1759        RequestConverter.buildTransitReplicationPeerSyncReplicationStateRequest(peerId,
1760          clusterState),
1761          (s, c, req, done) -> s.transitReplicationPeerSyncReplicationState(c, req, done),
1762          (resp) -> resp.getProcId(), new ReplicationProcedureBiConsumer(peerId,
1763            () -> "TRANSIT_REPLICATION_PEER_SYNCHRONOUS_REPLICATION_STATE"));
1764  }
1765
1766  @Override
1767  public CompletableFuture<Void> appendReplicationPeerTableCFs(String id,
1768      Map<TableName, List<String>> tableCfs) {
1769    if (tableCfs == null) {
1770      return failedFuture(new ReplicationException("tableCfs is null"));
1771    }
1772
1773    CompletableFuture<Void> future = new CompletableFuture<Void>();
1774    addListener(getReplicationPeerConfig(id), (peerConfig, error) -> {
1775      if (!completeExceptionally(future, error)) {
1776        ReplicationPeerConfig newPeerConfig =
1777          ReplicationPeerConfigUtil.appendTableCFsToReplicationPeerConfig(tableCfs, peerConfig);
1778        addListener(updateReplicationPeerConfig(id, newPeerConfig), (result, err) -> {
1779          if (!completeExceptionally(future, error)) {
1780            future.complete(result);
1781          }
1782        });
1783      }
1784    });
1785    return future;
1786  }
1787
1788  @Override
1789  public CompletableFuture<Void> removeReplicationPeerTableCFs(String id,
1790      Map<TableName, List<String>> tableCfs) {
1791    if (tableCfs == null) {
1792      return failedFuture(new ReplicationException("tableCfs is null"));
1793    }
1794
1795    CompletableFuture<Void> future = new CompletableFuture<Void>();
1796    addListener(getReplicationPeerConfig(id), (peerConfig, error) -> {
1797      if (!completeExceptionally(future, error)) {
1798        ReplicationPeerConfig newPeerConfig = null;
1799        try {
1800          newPeerConfig = ReplicationPeerConfigUtil
1801            .removeTableCFsFromReplicationPeerConfig(tableCfs, peerConfig, id);
1802        } catch (ReplicationException e) {
1803          future.completeExceptionally(e);
1804          return;
1805        }
1806        addListener(updateReplicationPeerConfig(id, newPeerConfig), (result, err) -> {
1807          if (!completeExceptionally(future, error)) {
1808            future.complete(result);
1809          }
1810        });
1811      }
1812    });
1813    return future;
1814  }
1815
1816  @Override
1817  public CompletableFuture<List<ReplicationPeerDescription>> listReplicationPeers() {
1818    return listReplicationPeers(RequestConverter.buildListReplicationPeersRequest(null));
1819  }
1820
1821  @Override
1822  public CompletableFuture<List<ReplicationPeerDescription>> listReplicationPeers(Pattern pattern) {
1823    Preconditions.checkNotNull(pattern,
1824      "pattern is null. If you don't specify a pattern, use listReplicationPeers() instead");
1825    return listReplicationPeers(RequestConverter.buildListReplicationPeersRequest(pattern));
1826  }
1827
1828  private CompletableFuture<List<ReplicationPeerDescription>> listReplicationPeers(
1829      ListReplicationPeersRequest request) {
1830    return this
1831        .<List<ReplicationPeerDescription>> newMasterCaller()
1832        .action(
1833          (controller, stub) -> this.<ListReplicationPeersRequest, ListReplicationPeersResponse,
1834              List<ReplicationPeerDescription>> call(controller, stub, request,
1835                (s, c, req, done) -> s.listReplicationPeers(c, req, done),
1836                (resp) -> resp.getPeerDescList().stream()
1837                    .map(ReplicationPeerConfigUtil::toReplicationPeerDescription)
1838                    .collect(Collectors.toList()))).call();
1839  }
1840
1841  @Override
1842  public CompletableFuture<List<TableCFs>> listReplicatedTableCFs() {
1843    CompletableFuture<List<TableCFs>> future = new CompletableFuture<List<TableCFs>>();
1844    addListener(listTableDescriptors(), (tables, error) -> {
1845      if (!completeExceptionally(future, error)) {
1846        List<TableCFs> replicatedTableCFs = new ArrayList<>();
1847        tables.forEach(table -> {
1848          Map<String, Integer> cfs = new HashMap<>();
1849          Stream.of(table.getColumnFamilies())
1850            .filter(column -> column.getScope() != HConstants.REPLICATION_SCOPE_LOCAL)
1851            .forEach(column -> {
1852              cfs.put(column.getNameAsString(), column.getScope());
1853            });
1854          if (!cfs.isEmpty()) {
1855            replicatedTableCFs.add(new TableCFs(table.getTableName(), cfs));
1856          }
1857        });
1858        future.complete(replicatedTableCFs);
1859      }
1860    });
1861    return future;
1862  }
1863
1864  @Override
1865  public CompletableFuture<Void> snapshot(SnapshotDescription snapshotDesc) {
1866    SnapshotProtos.SnapshotDescription snapshot =
1867      ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc);
1868    try {
1869      ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
1870    } catch (IllegalArgumentException e) {
1871      return failedFuture(e);
1872    }
1873    CompletableFuture<Void> future = new CompletableFuture<>();
1874    final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot).build();
1875    addListener(this.<Long> newMasterCaller()
1876      .action((controller, stub) -> this.<SnapshotRequest, SnapshotResponse, Long> call(controller,
1877        stub, request, (s, c, req, done) -> s.snapshot(c, req, done),
1878        resp -> resp.getExpectedTimeout()))
1879      .call(), (expectedTimeout, err) -> {
1880        if (err != null) {
1881          future.completeExceptionally(err);
1882          return;
1883        }
1884        TimerTask pollingTask = new TimerTask() {
1885          int tries = 0;
1886          long startTime = EnvironmentEdgeManager.currentTime();
1887          long endTime = startTime + expectedTimeout;
1888          long maxPauseTime = expectedTimeout / maxAttempts;
1889
1890          @Override
1891          public void run(Timeout timeout) throws Exception {
1892            if (EnvironmentEdgeManager.currentTime() < endTime) {
1893              addListener(isSnapshotFinished(snapshotDesc), (done, err2) -> {
1894                if (err2 != null) {
1895                  future.completeExceptionally(err2);
1896                } else if (done) {
1897                  future.complete(null);
1898                } else {
1899                  // retry again after pauseTime.
1900                  long pauseTime =
1901                    ConnectionUtils.getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
1902                  pauseTime = Math.min(pauseTime, maxPauseTime);
1903                  AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
1904                    TimeUnit.MILLISECONDS);
1905                }
1906              });
1907            } else {
1908              future.completeExceptionally(
1909                new SnapshotCreationException("Snapshot '" + snapshot.getName() +
1910                  "' wasn't completed in expectedTime:" + expectedTimeout + " ms", snapshotDesc));
1911            }
1912          }
1913        };
1914        AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
1915      });
1916    return future;
1917  }
1918
1919  @Override
1920  public CompletableFuture<Boolean> isSnapshotFinished(SnapshotDescription snapshot) {
1921    return this
1922        .<Boolean> newMasterCaller()
1923        .action(
1924          (controller, stub) -> this.<IsSnapshotDoneRequest, IsSnapshotDoneResponse, Boolean> call(
1925            controller,
1926            stub,
1927            IsSnapshotDoneRequest.newBuilder()
1928                .setSnapshot(ProtobufUtil.createHBaseProtosSnapshotDesc(snapshot)).build(), (s, c,
1929                req, done) -> s.isSnapshotDone(c, req, done), resp -> resp.getDone())).call();
1930  }
1931
1932  @Override
1933  public CompletableFuture<Void> restoreSnapshot(String snapshotName) {
1934    boolean takeFailSafeSnapshot = this.connection.getConfiguration().getBoolean(
1935      HConstants.SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT,
1936      HConstants.DEFAULT_SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT);
1937    return restoreSnapshot(snapshotName, takeFailSafeSnapshot);
1938  }
1939
1940  @Override
1941  public CompletableFuture<Void> restoreSnapshot(String snapshotName, boolean takeFailSafeSnapshot,
1942      boolean restoreAcl) {
1943    CompletableFuture<Void> future = new CompletableFuture<>();
1944    addListener(listSnapshots(Pattern.compile(snapshotName)), (snapshotDescriptions, err) -> {
1945      if (err != null) {
1946        future.completeExceptionally(err);
1947        return;
1948      }
1949      TableName tableName = null;
1950      if (snapshotDescriptions != null && !snapshotDescriptions.isEmpty()) {
1951        for (SnapshotDescription snap : snapshotDescriptions) {
1952          if (snap.getName().equals(snapshotName)) {
1953            tableName = snap.getTableName();
1954            break;
1955          }
1956        }
1957      }
1958      if (tableName == null) {
1959        future.completeExceptionally(new RestoreSnapshotException(
1960          "Unable to find the table name for snapshot=" + snapshotName));
1961        return;
1962      }
1963      final TableName finalTableName = tableName;
1964      addListener(tableExists(finalTableName), (exists, err2) -> {
1965        if (err2 != null) {
1966          future.completeExceptionally(err2);
1967        } else if (!exists) {
1968          // if table does not exist, then just clone snapshot into new table.
1969          completeConditionalOnFuture(future,
1970            internalRestoreSnapshot(snapshotName, finalTableName, restoreAcl));
1971        } else {
1972          addListener(isTableDisabled(finalTableName), (disabled, err4) -> {
1973            if (err4 != null) {
1974              future.completeExceptionally(err4);
1975            } else if (!disabled) {
1976              future.completeExceptionally(new TableNotDisabledException(finalTableName));
1977            } else {
1978              completeConditionalOnFuture(future,
1979                restoreSnapshot(snapshotName, finalTableName, takeFailSafeSnapshot, restoreAcl));
1980            }
1981          });
1982        }
1983      });
1984    });
1985    return future;
1986  }
1987
1988  private CompletableFuture<Void> restoreSnapshot(String snapshotName, TableName tableName,
1989      boolean takeFailSafeSnapshot, boolean restoreAcl) {
1990    if (takeFailSafeSnapshot) {
1991      CompletableFuture<Void> future = new CompletableFuture<>();
1992      // Step.1 Take a snapshot of the current state
1993      String failSafeSnapshotSnapshotNameFormat =
1994        this.connection.getConfiguration().get(HConstants.SNAPSHOT_RESTORE_FAILSAFE_NAME,
1995          HConstants.DEFAULT_SNAPSHOT_RESTORE_FAILSAFE_NAME);
1996      final String failSafeSnapshotSnapshotName =
1997        failSafeSnapshotSnapshotNameFormat.replace("{snapshot.name}", snapshotName)
1998          .replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.'))
1999          .replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTime()));
2000      LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
2001      addListener(snapshot(failSafeSnapshotSnapshotName, tableName), (ret, err) -> {
2002        if (err != null) {
2003          future.completeExceptionally(err);
2004        } else {
2005          // Step.2 Restore snapshot
2006          addListener(internalRestoreSnapshot(snapshotName, tableName, restoreAcl),
2007            (void2, err2) -> {
2008              if (err2 != null) {
2009                // Step.3.a Something went wrong during the restore and try to rollback.
2010                addListener(
2011                  internalRestoreSnapshot(failSafeSnapshotSnapshotName, tableName, restoreAcl),
2012                  (void3, err3) -> {
2013                    if (err3 != null) {
2014                      future.completeExceptionally(err3);
2015                    } else {
2016                      String msg =
2017                        "Restore snapshot=" + snapshotName + " failed. Rollback to snapshot=" +
2018                          failSafeSnapshotSnapshotName + " succeeded.";
2019                      future.completeExceptionally(new RestoreSnapshotException(msg, err2));
2020                    }
2021                  });
2022              } else {
2023                // Step.3.b If the restore is succeeded, delete the pre-restore snapshot.
2024                LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
2025                addListener(deleteSnapshot(failSafeSnapshotSnapshotName), (ret3, err3) -> {
2026                  if (err3 != null) {
2027                    LOG.error(
2028                      "Unable to remove the failsafe snapshot: " + failSafeSnapshotSnapshotName,
2029                      err3);
2030                  }
2031                  future.complete(ret3);
2032                });
2033              }
2034            });
2035        }
2036      });
2037      return future;
2038    } else {
2039      return internalRestoreSnapshot(snapshotName, tableName, restoreAcl);
2040    }
2041  }
2042
2043  private <T> void completeConditionalOnFuture(CompletableFuture<T> dependentFuture,
2044      CompletableFuture<T> parentFuture) {
2045    addListener(parentFuture, (res, err) -> {
2046      if (err != null) {
2047        dependentFuture.completeExceptionally(err);
2048      } else {
2049        dependentFuture.complete(res);
2050      }
2051    });
2052  }
2053
2054  @Override
2055  public CompletableFuture<Void> cloneSnapshot(String snapshotName, TableName tableName,
2056      boolean restoreAcl) {
2057    CompletableFuture<Void> future = new CompletableFuture<>();
2058    addListener(tableExists(tableName), (exists, err) -> {
2059      if (err != null) {
2060        future.completeExceptionally(err);
2061      } else if (exists) {
2062        future.completeExceptionally(new TableExistsException(tableName));
2063      } else {
2064        completeConditionalOnFuture(future,
2065          internalRestoreSnapshot(snapshotName, tableName, restoreAcl));
2066      }
2067    });
2068    return future;
2069  }
2070
2071  private CompletableFuture<Void> internalRestoreSnapshot(String snapshotName, TableName tableName,
2072      boolean restoreAcl) {
2073    SnapshotProtos.SnapshotDescription snapshot = SnapshotProtos.SnapshotDescription.newBuilder()
2074      .setName(snapshotName).setTable(tableName.getNameAsString()).build();
2075    try {
2076      ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
2077    } catch (IllegalArgumentException e) {
2078      return failedFuture(e);
2079    }
2080    return waitProcedureResult(this.<Long> newMasterCaller().action((controller, stub) -> this
2081      .<RestoreSnapshotRequest, RestoreSnapshotResponse, Long> call(controller, stub,
2082        RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot).setNonceGroup(ng.getNonceGroup())
2083          .setNonce(ng.newNonce()).setRestoreACL(restoreAcl).build(),
2084        (s, c, req, done) -> s.restoreSnapshot(c, req, done), (resp) -> resp.getProcId()))
2085      .call());
2086  }
2087
2088  @Override
2089  public CompletableFuture<List<SnapshotDescription>> listSnapshots() {
2090    return getCompletedSnapshots(null);
2091  }
2092
2093  @Override
2094  public CompletableFuture<List<SnapshotDescription>> listSnapshots(Pattern pattern) {
2095    Preconditions.checkNotNull(pattern,
2096      "pattern is null. If you don't specify a pattern, use listSnapshots() instead");
2097    return getCompletedSnapshots(pattern);
2098  }
2099
2100  private CompletableFuture<List<SnapshotDescription>> getCompletedSnapshots(Pattern pattern) {
2101    return this.<List<SnapshotDescription>> newMasterCaller().action((controller, stub) -> this
2102        .<GetCompletedSnapshotsRequest, GetCompletedSnapshotsResponse, List<SnapshotDescription>>
2103        call(controller, stub, GetCompletedSnapshotsRequest.newBuilder().build(),
2104          (s, c, req, done) -> s.getCompletedSnapshots(c, req, done),
2105          resp -> ProtobufUtil.toSnapshotDescriptionList(resp, pattern)))
2106        .call();
2107  }
2108
2109  @Override
2110  public CompletableFuture<List<SnapshotDescription>> listTableSnapshots(Pattern tableNamePattern) {
2111    Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
2112        + " If you don't specify a tableNamePattern, use listSnapshots() instead");
2113    return getCompletedSnapshots(tableNamePattern, null);
2114  }
2115
2116  @Override
2117  public CompletableFuture<List<SnapshotDescription>> listTableSnapshots(Pattern tableNamePattern,
2118      Pattern snapshotNamePattern) {
2119    Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
2120        + " If you don't specify a tableNamePattern, use listSnapshots(Pattern) instead");
2121    Preconditions.checkNotNull(snapshotNamePattern, "snapshotNamePattern is null."
2122        + " If you don't specify a snapshotNamePattern, use listTableSnapshots(Pattern) instead");
2123    return getCompletedSnapshots(tableNamePattern, snapshotNamePattern);
2124  }
2125
2126  private CompletableFuture<List<SnapshotDescription>> getCompletedSnapshots(
2127      Pattern tableNamePattern, Pattern snapshotNamePattern) {
2128    CompletableFuture<List<SnapshotDescription>> future = new CompletableFuture<>();
2129    addListener(listTableNames(tableNamePattern, false), (tableNames, err) -> {
2130      if (err != null) {
2131        future.completeExceptionally(err);
2132        return;
2133      }
2134      if (tableNames == null || tableNames.size() <= 0) {
2135        future.complete(Collections.emptyList());
2136        return;
2137      }
2138      addListener(getCompletedSnapshots(snapshotNamePattern), (snapshotDescList, err2) -> {
2139        if (err2 != null) {
2140          future.completeExceptionally(err2);
2141          return;
2142        }
2143        if (snapshotDescList == null || snapshotDescList.isEmpty()) {
2144          future.complete(Collections.emptyList());
2145          return;
2146        }
2147        future.complete(snapshotDescList.stream()
2148          .filter(snap -> (snap != null && tableNames.contains(snap.getTableName())))
2149          .collect(Collectors.toList()));
2150      });
2151    });
2152    return future;
2153  }
2154
2155  @Override
2156  public CompletableFuture<Void> deleteSnapshot(String snapshotName) {
2157    return internalDeleteSnapshot(new SnapshotDescription(snapshotName));
2158  }
2159
2160  @Override
2161  public CompletableFuture<Void> deleteSnapshots() {
2162    return internalDeleteSnapshots(null, null);
2163  }
2164
2165  @Override
2166  public CompletableFuture<Void> deleteSnapshots(Pattern snapshotNamePattern) {
2167    Preconditions.checkNotNull(snapshotNamePattern, "snapshotNamePattern is null."
2168        + " If you don't specify a snapshotNamePattern, use deleteSnapshots() instead");
2169    return internalDeleteSnapshots(null, snapshotNamePattern);
2170  }
2171
2172  @Override
2173  public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern) {
2174    Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
2175        + " If you don't specify a tableNamePattern, use deleteSnapshots() instead");
2176    return internalDeleteSnapshots(tableNamePattern, null);
2177  }
2178
2179  @Override
2180  public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern,
2181      Pattern snapshotNamePattern) {
2182    Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
2183        + " If you don't specify a tableNamePattern, use deleteSnapshots(Pattern) instead");
2184    Preconditions.checkNotNull(snapshotNamePattern, "snapshotNamePattern is null."
2185        + " If you don't specify a snapshotNamePattern, use deleteSnapshots(Pattern) instead");
2186    return internalDeleteSnapshots(tableNamePattern, snapshotNamePattern);
2187  }
2188
2189  private CompletableFuture<Void> internalDeleteSnapshots(Pattern tableNamePattern,
2190      Pattern snapshotNamePattern) {
2191    CompletableFuture<List<SnapshotDescription>> listSnapshotsFuture;
2192    if (tableNamePattern == null) {
2193      listSnapshotsFuture = getCompletedSnapshots(snapshotNamePattern);
2194    } else {
2195      listSnapshotsFuture = getCompletedSnapshots(tableNamePattern, snapshotNamePattern);
2196    }
2197    CompletableFuture<Void> future = new CompletableFuture<>();
2198    addListener(listSnapshotsFuture, ((snapshotDescriptions, err) -> {
2199      if (err != null) {
2200        future.completeExceptionally(err);
2201        return;
2202      }
2203      if (snapshotDescriptions == null || snapshotDescriptions.isEmpty()) {
2204        future.complete(null);
2205        return;
2206      }
2207      addListener(CompletableFuture.allOf(snapshotDescriptions.stream()
2208        .map(this::internalDeleteSnapshot).toArray(CompletableFuture[]::new)), (v, e) -> {
2209          if (e != null) {
2210            future.completeExceptionally(e);
2211          } else {
2212            future.complete(v);
2213          }
2214        });
2215    }));
2216    return future;
2217  }
2218
2219  private CompletableFuture<Void> internalDeleteSnapshot(SnapshotDescription snapshot) {
2220    return this
2221        .<Void> newMasterCaller()
2222        .action(
2223          (controller, stub) -> this.<DeleteSnapshotRequest, DeleteSnapshotResponse, Void> call(
2224            controller,
2225            stub,
2226            DeleteSnapshotRequest.newBuilder()
2227                .setSnapshot(ProtobufUtil.createHBaseProtosSnapshotDesc(snapshot)).build(), (s, c,
2228                req, done) -> s.deleteSnapshot(c, req, done), resp -> null)).call();
2229  }
2230
2231  @Override
2232  public CompletableFuture<Void> execProcedure(String signature, String instance,
2233      Map<String, String> props) {
2234    CompletableFuture<Void> future = new CompletableFuture<>();
2235    ProcedureDescription procDesc =
2236      ProtobufUtil.buildProcedureDescription(signature, instance, props);
2237    addListener(this.<Long> newMasterCaller()
2238      .action((controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, Long> call(
2239        controller, stub, ExecProcedureRequest.newBuilder().setProcedure(procDesc).build(),
2240        (s, c, req, done) -> s.execProcedure(c, req, done), resp -> resp.getExpectedTimeout()))
2241      .call(), (expectedTimeout, err) -> {
2242        if (err != null) {
2243          future.completeExceptionally(err);
2244          return;
2245        }
2246        TimerTask pollingTask = new TimerTask() {
2247          int tries = 0;
2248          long startTime = EnvironmentEdgeManager.currentTime();
2249          long endTime = startTime + expectedTimeout;
2250          long maxPauseTime = expectedTimeout / maxAttempts;
2251
2252          @Override
2253          public void run(Timeout timeout) throws Exception {
2254            if (EnvironmentEdgeManager.currentTime() < endTime) {
2255              addListener(isProcedureFinished(signature, instance, props), (done, err2) -> {
2256                if (err2 != null) {
2257                  future.completeExceptionally(err2);
2258                  return;
2259                }
2260                if (done) {
2261                  future.complete(null);
2262                } else {
2263                  // retry again after pauseTime.
2264                  long pauseTime =
2265                    ConnectionUtils.getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
2266                  pauseTime = Math.min(pauseTime, maxPauseTime);
2267                  AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
2268                    TimeUnit.MICROSECONDS);
2269                }
2270              });
2271            } else {
2272              future.completeExceptionally(new IOException("Procedure '" + signature + " : " +
2273                instance + "' wasn't completed in expectedTime:" + expectedTimeout + " ms"));
2274            }
2275          }
2276        };
2277        // Queue the polling task into RETRY_TIMER to poll procedure state asynchronously.
2278        AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
2279      });
2280    return future;
2281  }
2282
2283  @Override
2284  public CompletableFuture<byte[]> execProcedureWithReturn(String signature, String instance,
2285      Map<String, String> props) {
2286    ProcedureDescription proDesc =
2287        ProtobufUtil.buildProcedureDescription(signature, instance, props);
2288    return this.<byte[]> newMasterCaller()
2289        .action(
2290          (controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, byte[]> call(
2291            controller, stub, ExecProcedureRequest.newBuilder().setProcedure(proDesc).build(),
2292            (s, c, req, done) -> s.execProcedureWithRet(c, req, done),
2293            resp -> resp.hasReturnData() ? resp.getReturnData().toByteArray() : null))
2294        .call();
2295  }
2296
2297  @Override
2298  public CompletableFuture<Boolean> isProcedureFinished(String signature, String instance,
2299      Map<String, String> props) {
2300    ProcedureDescription proDesc =
2301        ProtobufUtil.buildProcedureDescription(signature, instance, props);
2302    return this.<Boolean> newMasterCaller()
2303        .action((controller, stub) -> this
2304            .<IsProcedureDoneRequest, IsProcedureDoneResponse, Boolean> call(controller, stub,
2305              IsProcedureDoneRequest.newBuilder().setProcedure(proDesc).build(),
2306              (s, c, req, done) -> s.isProcedureDone(c, req, done), resp -> resp.getDone()))
2307        .call();
2308  }
2309
2310  @Override
2311  public CompletableFuture<Boolean> abortProcedure(long procId, boolean mayInterruptIfRunning) {
2312    return this.<Boolean> newMasterCaller().action(
2313      (controller, stub) -> this.<AbortProcedureRequest, AbortProcedureResponse, Boolean> call(
2314        controller, stub, AbortProcedureRequest.newBuilder().setProcId(procId).build(),
2315        (s, c, req, done) -> s.abortProcedure(c, req, done), resp -> resp.getIsProcedureAborted()))
2316        .call();
2317  }
2318
2319  @Override
2320  public CompletableFuture<String> getProcedures() {
2321    return this
2322        .<String> newMasterCaller()
2323        .action(
2324          (controller, stub) -> this
2325              .<GetProceduresRequest, GetProceduresResponse, String> call(
2326                controller, stub, GetProceduresRequest.newBuilder().build(),
2327                (s, c, req, done) -> s.getProcedures(c, req, done),
2328                resp -> ProtobufUtil.toProcedureJson(resp.getProcedureList()))).call();
2329  }
2330
2331  @Override
2332  public CompletableFuture<String> getLocks() {
2333    return this
2334        .<String> newMasterCaller()
2335        .action(
2336          (controller, stub) -> this.<GetLocksRequest, GetLocksResponse, String> call(
2337            controller, stub, GetLocksRequest.newBuilder().build(),
2338            (s, c, req, done) -> s.getLocks(c, req, done),
2339            resp -> ProtobufUtil.toLockJson(resp.getLockList()))).call();
2340  }
2341
2342  @Override
2343  public CompletableFuture<Void> decommissionRegionServers(
2344      List<ServerName> servers, boolean offload) {
2345    return this.<Void> newMasterCaller()
2346        .action((controller, stub) -> this
2347          .<DecommissionRegionServersRequest, DecommissionRegionServersResponse, Void> call(
2348            controller, stub,
2349              RequestConverter.buildDecommissionRegionServersRequest(servers, offload),
2350            (s, c, req, done) -> s.decommissionRegionServers(c, req, done), resp -> null))
2351        .call();
2352  }
2353
2354  @Override
2355  public CompletableFuture<List<ServerName>> listDecommissionedRegionServers() {
2356    return this.<List<ServerName>> newMasterCaller()
2357        .action((controller, stub) -> this
2358          .<ListDecommissionedRegionServersRequest, ListDecommissionedRegionServersResponse,
2359            List<ServerName>> call(
2360              controller, stub, ListDecommissionedRegionServersRequest.newBuilder().build(),
2361              (s, c, req, done) -> s.listDecommissionedRegionServers(c, req, done),
2362              resp -> resp.getServerNameList().stream().map(ProtobufUtil::toServerName)
2363                  .collect(Collectors.toList())))
2364        .call();
2365  }
2366
2367  @Override
2368  public CompletableFuture<Void> recommissionRegionServer(ServerName server,
2369      List<byte[]> encodedRegionNames) {
2370    return this.<Void> newMasterCaller()
2371        .action((controller, stub) ->
2372            this.<RecommissionRegionServerRequest, RecommissionRegionServerResponse, Void> call(
2373                controller, stub, RequestConverter.buildRecommissionRegionServerRequest(
2374                    server, encodedRegionNames), (s, c, req, done) -> s.recommissionRegionServer(
2375                        c, req, done), resp -> null)).call();
2376  }
2377
2378  /**
2379   * Get the region location for the passed region name. The region name may be a full region name
2380   * or encoded region name. If the region does not found, then it'll throw an
2381   * UnknownRegionException wrapped by a {@link CompletableFuture}
2382   * @param regionNameOrEncodedRegionName region name or encoded region name
2383   * @return region location, wrapped by a {@link CompletableFuture}
2384   */
2385  CompletableFuture<HRegionLocation> getRegionLocation(byte[] regionNameOrEncodedRegionName) {
2386    if (regionNameOrEncodedRegionName == null) {
2387      return failedFuture(new IllegalArgumentException("Passed region name can't be null"));
2388    }
2389
2390    CompletableFuture<Optional<HRegionLocation>> future;
2391    if (RegionInfo.isEncodedRegionName(regionNameOrEncodedRegionName)) {
2392      String encodedName = Bytes.toString(regionNameOrEncodedRegionName);
2393      if (encodedName.length() < RegionInfo.MD5_HEX_LENGTH) {
2394        // old format encodedName, should be meta region
2395        future = connection.registry.getMetaRegionLocations()
2396          .thenApply(locs -> Stream.of(locs.getRegionLocations())
2397            .filter(loc -> loc.getRegion().getEncodedName().equals(encodedName)).findFirst());
2398      } else {
2399        future = ClientMetaTableAccessor.getRegionLocationWithEncodedName(metaTable,
2400          regionNameOrEncodedRegionName);
2401      }
2402    } else {
2403      // Not all regionNameOrEncodedRegionName here is going to be a valid region name,
2404      // it needs to throw out IllegalArgumentException in case tableName is passed in.
2405      RegionInfo regionInfo;
2406      try {
2407        regionInfo = CatalogFamilyFormat.parseRegionInfoFromRegionName(
2408          regionNameOrEncodedRegionName);
2409      } catch (IOException ioe) {
2410        return failedFuture(new IllegalArgumentException(ioe.getMessage()));
2411      }
2412
2413      if (regionInfo.isMetaRegion()) {
2414        future = connection.registry.getMetaRegionLocations()
2415          .thenApply(locs -> Stream.of(locs.getRegionLocations())
2416            .filter(loc -> loc.getRegion().getReplicaId() == regionInfo.getReplicaId())
2417            .findFirst());
2418      } else {
2419        future =
2420          ClientMetaTableAccessor.getRegionLocation(metaTable, regionNameOrEncodedRegionName);
2421      }
2422    }
2423
2424    CompletableFuture<HRegionLocation> returnedFuture = new CompletableFuture<>();
2425    addListener(future, (location, err) -> {
2426      if (err != null) {
2427        returnedFuture.completeExceptionally(err);
2428        return;
2429      }
2430      if (!location.isPresent() || location.get().getRegion() == null) {
2431        returnedFuture.completeExceptionally(
2432          new UnknownRegionException("Invalid region name or encoded region name: " +
2433            Bytes.toStringBinary(regionNameOrEncodedRegionName)));
2434      } else {
2435        returnedFuture.complete(location.get());
2436      }
2437    });
2438    return returnedFuture;
2439  }
2440
2441  /**
2442   * Get the region info for the passed region name. The region name may be a full region name or
2443   * encoded region name. If the region does not found, then it'll throw an UnknownRegionException
2444   * wrapped by a {@link CompletableFuture}
2445   * @return region info, wrapped by a {@link CompletableFuture}
2446   */
2447  private CompletableFuture<RegionInfo> getRegionInfo(byte[] regionNameOrEncodedRegionName) {
2448    if (regionNameOrEncodedRegionName == null) {
2449      return failedFuture(new IllegalArgumentException("Passed region name can't be null"));
2450    }
2451
2452    if (Bytes.equals(regionNameOrEncodedRegionName,
2453      RegionInfoBuilder.FIRST_META_REGIONINFO.getRegionName()) ||
2454      Bytes.equals(regionNameOrEncodedRegionName,
2455        RegionInfoBuilder.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) {
2456      return CompletableFuture.completedFuture(RegionInfoBuilder.FIRST_META_REGIONINFO);
2457    }
2458
2459    CompletableFuture<RegionInfo> future = new CompletableFuture<>();
2460    addListener(getRegionLocation(regionNameOrEncodedRegionName), (location, err) -> {
2461      if (err != null) {
2462        future.completeExceptionally(err);
2463      } else {
2464        future.complete(location.getRegion());
2465      }
2466    });
2467    return future;
2468  }
2469
2470  private byte[][] getSplitKeys(byte[] startKey, byte[] endKey, int numRegions) {
2471    if (numRegions < 3) {
2472      throw new IllegalArgumentException("Must create at least three regions");
2473    } else if (Bytes.compareTo(startKey, endKey) >= 0) {
2474      throw new IllegalArgumentException("Start key must be smaller than end key");
2475    }
2476    if (numRegions == 3) {
2477      return new byte[][] { startKey, endKey };
2478    }
2479    byte[][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
2480    if (splitKeys == null || splitKeys.length != numRegions - 1) {
2481      throw new IllegalArgumentException("Unable to split key range into enough regions");
2482    }
2483    return splitKeys;
2484  }
2485
2486  private void verifySplitKeys(byte[][] splitKeys) {
2487    Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
2488    // Verify there are no duplicate split keys
2489    byte[] lastKey = null;
2490    for (byte[] splitKey : splitKeys) {
2491      if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
2492        throw new IllegalArgumentException("Empty split key must not be passed in the split keys.");
2493      }
2494      if (lastKey != null && Bytes.equals(splitKey, lastKey)) {
2495        throw new IllegalArgumentException("All split keys must be unique, " + "found duplicate: "
2496            + Bytes.toStringBinary(splitKey) + ", " + Bytes.toStringBinary(lastKey));
2497      }
2498      lastKey = splitKey;
2499    }
2500  }
2501
2502  private static abstract class ProcedureBiConsumer implements BiConsumer<Void, Throwable> {
2503
2504    abstract void onFinished();
2505
2506    abstract void onError(Throwable error);
2507
2508    @Override
2509    public void accept(Void v, Throwable error) {
2510      if (error != null) {
2511        onError(error);
2512        return;
2513      }
2514      onFinished();
2515    }
2516  }
2517
2518  private static abstract class TableProcedureBiConsumer extends ProcedureBiConsumer {
2519    protected final TableName tableName;
2520
2521    TableProcedureBiConsumer(TableName tableName) {
2522      this.tableName = tableName;
2523    }
2524
2525    abstract String getOperationType();
2526
2527    String getDescription() {
2528      return "Operation: " + getOperationType() + ", " + "Table Name: "
2529          + tableName.getNameWithNamespaceInclAsString();
2530    }
2531
2532    @Override
2533    void onFinished() {
2534      LOG.info(getDescription() + " completed");
2535    }
2536
2537    @Override
2538    void onError(Throwable error) {
2539      LOG.info(getDescription() + " failed with " + error.getMessage());
2540    }
2541  }
2542
2543  private static abstract class NamespaceProcedureBiConsumer extends ProcedureBiConsumer {
2544    protected final String namespaceName;
2545
2546    NamespaceProcedureBiConsumer(String namespaceName) {
2547      this.namespaceName = namespaceName;
2548    }
2549
2550    abstract String getOperationType();
2551
2552    String getDescription() {
2553      return "Operation: " + getOperationType() + ", Namespace: " + namespaceName;
2554    }
2555
2556    @Override
2557    void onFinished() {
2558      LOG.info(getDescription() + " completed");
2559    }
2560
2561    @Override
2562    void onError(Throwable error) {
2563      LOG.info(getDescription() + " failed with " + error.getMessage());
2564    }
2565  }
2566
2567  private static class CreateTableProcedureBiConsumer extends TableProcedureBiConsumer {
2568
2569    CreateTableProcedureBiConsumer(TableName tableName) {
2570      super(tableName);
2571    }
2572
2573    @Override
2574    String getOperationType() {
2575      return "CREATE";
2576    }
2577  }
2578
2579  private static class ModifyTableProcedureBiConsumer extends TableProcedureBiConsumer {
2580
2581    ModifyTableProcedureBiConsumer(AsyncAdmin admin, TableName tableName) {
2582      super(tableName);
2583    }
2584
2585    @Override
2586    String getOperationType() {
2587      return "ENABLE";
2588    }
2589  }
2590
2591  private class DeleteTableProcedureBiConsumer extends TableProcedureBiConsumer {
2592
2593    DeleteTableProcedureBiConsumer(TableName tableName) {
2594      super(tableName);
2595    }
2596
2597    @Override
2598    String getOperationType() {
2599      return "DELETE";
2600    }
2601
2602    @Override
2603    void onFinished() {
2604      connection.getLocator().clearCache(this.tableName);
2605      super.onFinished();
2606    }
2607  }
2608
2609  private static class TruncateTableProcedureBiConsumer extends TableProcedureBiConsumer {
2610
2611    TruncateTableProcedureBiConsumer(TableName tableName) {
2612      super(tableName);
2613    }
2614
2615    @Override
2616    String getOperationType() {
2617      return "TRUNCATE";
2618    }
2619  }
2620
2621  private static class EnableTableProcedureBiConsumer extends TableProcedureBiConsumer {
2622
2623    EnableTableProcedureBiConsumer(TableName tableName) {
2624      super(tableName);
2625    }
2626
2627    @Override
2628    String getOperationType() {
2629      return "ENABLE";
2630    }
2631  }
2632
2633  private static class DisableTableProcedureBiConsumer extends TableProcedureBiConsumer {
2634
2635    DisableTableProcedureBiConsumer(TableName tableName) {
2636      super(tableName);
2637    }
2638
2639    @Override
2640    String getOperationType() {
2641      return "DISABLE";
2642    }
2643  }
2644
2645  private static class AddColumnFamilyProcedureBiConsumer extends TableProcedureBiConsumer {
2646
2647    AddColumnFamilyProcedureBiConsumer(TableName tableName) {
2648      super(tableName);
2649    }
2650
2651    @Override
2652    String getOperationType() {
2653      return "ADD_COLUMN_FAMILY";
2654    }
2655  }
2656
2657  private static class DeleteColumnFamilyProcedureBiConsumer extends TableProcedureBiConsumer {
2658
2659    DeleteColumnFamilyProcedureBiConsumer(TableName tableName) {
2660      super(tableName);
2661    }
2662
2663    @Override
2664    String getOperationType() {
2665      return "DELETE_COLUMN_FAMILY";
2666    }
2667  }
2668
2669  private static class ModifyColumnFamilyProcedureBiConsumer extends TableProcedureBiConsumer {
2670
2671    ModifyColumnFamilyProcedureBiConsumer(TableName tableName) {
2672      super(tableName);
2673    }
2674
2675    @Override
2676    String getOperationType() {
2677      return "MODIFY_COLUMN_FAMILY";
2678    }
2679  }
2680
2681  private static class CreateNamespaceProcedureBiConsumer extends NamespaceProcedureBiConsumer {
2682
2683    CreateNamespaceProcedureBiConsumer(String namespaceName) {
2684      super(namespaceName);
2685    }
2686
2687    @Override
2688    String getOperationType() {
2689      return "CREATE_NAMESPACE";
2690    }
2691  }
2692
2693  private static class DeleteNamespaceProcedureBiConsumer extends NamespaceProcedureBiConsumer {
2694
2695    DeleteNamespaceProcedureBiConsumer(String namespaceName) {
2696      super(namespaceName);
2697    }
2698
2699    @Override
2700    String getOperationType() {
2701      return "DELETE_NAMESPACE";
2702    }
2703  }
2704
2705  private static class ModifyNamespaceProcedureBiConsumer extends NamespaceProcedureBiConsumer {
2706
2707    ModifyNamespaceProcedureBiConsumer(String namespaceName) {
2708      super(namespaceName);
2709    }
2710
2711    @Override
2712    String getOperationType() {
2713      return "MODIFY_NAMESPACE";
2714    }
2715  }
2716
2717  private static class MergeTableRegionProcedureBiConsumer extends TableProcedureBiConsumer {
2718
2719    MergeTableRegionProcedureBiConsumer(TableName tableName) {
2720      super(tableName);
2721    }
2722
2723    @Override
2724    String getOperationType() {
2725      return "MERGE_REGIONS";
2726    }
2727  }
2728
2729  private static class SplitTableRegionProcedureBiConsumer extends TableProcedureBiConsumer {
2730
2731    SplitTableRegionProcedureBiConsumer(TableName tableName) {
2732      super(tableName);
2733    }
2734
2735    @Override
2736    String getOperationType() {
2737      return "SPLIT_REGION";
2738    }
2739  }
2740
2741  private static class ReplicationProcedureBiConsumer extends ProcedureBiConsumer {
2742    private final String peerId;
2743    private final Supplier<String> getOperation;
2744
2745    ReplicationProcedureBiConsumer(String peerId, Supplier<String> getOperation) {
2746      this.peerId = peerId;
2747      this.getOperation = getOperation;
2748    }
2749
2750    String getDescription() {
2751      return "Operation: " + getOperation.get() + ", peerId: " + peerId;
2752    }
2753
2754    @Override
2755    void onFinished() {
2756      LOG.info(getDescription() + " completed");
2757    }
2758
2759    @Override
2760    void onError(Throwable error) {
2761      LOG.info(getDescription() + " failed with " + error.getMessage());
2762    }
2763  }
2764
2765  private CompletableFuture<Void> waitProcedureResult(CompletableFuture<Long> procFuture) {
2766    CompletableFuture<Void> future = new CompletableFuture<>();
2767    addListener(procFuture, (procId, error) -> {
2768      if (error != null) {
2769        future.completeExceptionally(error);
2770        return;
2771      }
2772      getProcedureResult(procId, future, 0);
2773    });
2774    return future;
2775  }
2776
2777  private void getProcedureResult(long procId, CompletableFuture<Void> future, int retries) {
2778    addListener(
2779      this.<GetProcedureResultResponse> newMasterCaller()
2780        .action((controller, stub) -> this
2781          .<GetProcedureResultRequest, GetProcedureResultResponse, GetProcedureResultResponse> call(
2782            controller, stub, GetProcedureResultRequest.newBuilder().setProcId(procId).build(),
2783            (s, c, req, done) -> s.getProcedureResult(c, req, done), (resp) -> resp))
2784        .call(),
2785      (response, error) -> {
2786        if (error != null) {
2787          LOG.warn("failed to get the procedure result procId={}", procId,
2788            ConnectionUtils.translateException(error));
2789          retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1),
2790            ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS);
2791          return;
2792        }
2793        if (response.getState() == GetProcedureResultResponse.State.RUNNING) {
2794          retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1),
2795            ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS);
2796          return;
2797        }
2798        if (response.hasException()) {
2799          IOException ioe = ForeignExceptionUtil.toIOException(response.getException());
2800          future.completeExceptionally(ioe);
2801        } else {
2802          future.complete(null);
2803        }
2804      });
2805  }
2806
2807  private <T> CompletableFuture<T> failedFuture(Throwable error) {
2808    CompletableFuture<T> future = new CompletableFuture<>();
2809    future.completeExceptionally(error);
2810    return future;
2811  }
2812
2813  private <T> boolean completeExceptionally(CompletableFuture<T> future, Throwable error) {
2814    if (error != null) {
2815      future.completeExceptionally(error);
2816      return true;
2817    }
2818    return false;
2819  }
2820
2821  @Override
2822  public CompletableFuture<ClusterMetrics> getClusterMetrics() {
2823    return getClusterMetrics(EnumSet.allOf(Option.class));
2824  }
2825
2826  @Override
2827  public CompletableFuture<ClusterMetrics> getClusterMetrics(EnumSet<Option> options) {
2828    return this
2829        .<ClusterMetrics> newMasterCaller()
2830        .action(
2831          (controller, stub) -> this
2832              .<GetClusterStatusRequest, GetClusterStatusResponse, ClusterMetrics> call(controller,
2833                stub, RequestConverter.buildGetClusterStatusRequest(options),
2834                (s, c, req, done) -> s.getClusterStatus(c, req, done),
2835                resp -> ClusterMetricsBuilder.toClusterMetrics(resp.getClusterStatus()))).call();
2836  }
2837
2838  @Override
2839  public CompletableFuture<Void> shutdown() {
2840    return this.<Void> newMasterCaller().priority(HIGH_QOS)
2841      .action((controller, stub) -> this.<ShutdownRequest, ShutdownResponse, Void> call(controller,
2842        stub, ShutdownRequest.newBuilder().build(), (s, c, req, done) -> s.shutdown(c, req, done),
2843        resp -> null))
2844      .call();
2845  }
2846
2847  @Override
2848  public CompletableFuture<Void> stopMaster() {
2849    return this.<Void> newMasterCaller().priority(HIGH_QOS)
2850      .action((controller, stub) -> this.<StopMasterRequest, StopMasterResponse, Void> call(
2851        controller, stub, StopMasterRequest.newBuilder().build(),
2852        (s, c, req, done) -> s.stopMaster(c, req, done), resp -> null))
2853      .call();
2854  }
2855
2856  @Override
2857  public CompletableFuture<Void> stopRegionServer(ServerName serverName) {
2858    StopServerRequest request = RequestConverter
2859      .buildStopServerRequest("Called by admin client " + this.connection.toString());
2860    return this.<Void> newAdminCaller().priority(HIGH_QOS)
2861      .action((controller, stub) -> this.<StopServerRequest, StopServerResponse, Void> adminCall(
2862        controller, stub, request, (s, c, req, done) -> s.stopServer(controller, req, done),
2863        resp -> null))
2864      .serverName(serverName).call();
2865  }
2866
2867  @Override
2868  public CompletableFuture<Void> updateConfiguration(ServerName serverName) {
2869    return this
2870        .<Void> newAdminCaller()
2871        .action(
2872          (controller, stub) -> this
2873              .<UpdateConfigurationRequest, UpdateConfigurationResponse, Void> adminCall(
2874                controller, stub, UpdateConfigurationRequest.getDefaultInstance(),
2875                (s, c, req, done) -> s.updateConfiguration(controller, req, done), resp -> null))
2876        .serverName(serverName).call();
2877  }
2878
2879  @Override
2880  public CompletableFuture<Void> updateConfiguration() {
2881    CompletableFuture<Void> future = new CompletableFuture<Void>();
2882    addListener(
2883      getClusterMetrics(EnumSet.of(Option.SERVERS_NAME, Option.MASTER, Option.BACKUP_MASTERS)),
2884      (status, err) -> {
2885        if (err != null) {
2886          future.completeExceptionally(err);
2887        } else {
2888          List<CompletableFuture<Void>> futures = new ArrayList<>();
2889          status.getServersName().forEach(server -> futures.add(updateConfiguration(server)));
2890          futures.add(updateConfiguration(status.getMasterName()));
2891          status.getBackupMasterNames().forEach(master -> futures.add(updateConfiguration(master)));
2892          addListener(
2893            CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
2894            (result, err2) -> {
2895              if (err2 != null) {
2896                future.completeExceptionally(err2);
2897              } else {
2898                future.complete(result);
2899              }
2900            });
2901        }
2902      });
2903    return future;
2904  }
2905
2906  @Override
2907  public CompletableFuture<Void> updateConfiguration(String groupName) {
2908    CompletableFuture<Void> future = new CompletableFuture<Void>();
2909    addListener(
2910      getRSGroup(groupName),
2911      (rsGroupInfo, err) -> {
2912        if (err != null) {
2913          future.completeExceptionally(err);
2914        } else if (rsGroupInfo == null) {
2915          future.completeExceptionally(
2916            new IllegalArgumentException("Group does not exist: " + groupName));
2917        } else {
2918          addListener(getClusterMetrics(EnumSet.of(Option.SERVERS_NAME)), (status, err2) -> {
2919            if (err2 != null) {
2920              future.completeExceptionally(err2);
2921            } else {
2922              List<CompletableFuture<Void>> futures = new ArrayList<>();
2923              List<ServerName> groupServers = status.getServersName().stream().filter(
2924                s -> rsGroupInfo.containsServer(s.getAddress())).collect(Collectors.toList());
2925              groupServers.forEach(server -> futures.add(updateConfiguration(server)));
2926              addListener(
2927                CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
2928                (result, err3) -> {
2929                  if (err3 != null) {
2930                    future.completeExceptionally(err3);
2931                  } else {
2932                    future.complete(result);
2933                  }
2934                });
2935            }
2936          });
2937        }
2938      });
2939    return future;
2940  }
2941
2942  @Override
2943  public CompletableFuture<Void> rollWALWriter(ServerName serverName) {
2944    return this
2945        .<Void> newAdminCaller()
2946        .action(
2947          (controller, stub) -> this.<RollWALWriterRequest, RollWALWriterResponse, Void> adminCall(
2948            controller, stub, RequestConverter.buildRollWALWriterRequest(),
2949            (s, c, req, done) -> s.rollWALWriter(controller, req, done), resp -> null))
2950        .serverName(serverName).call();
2951  }
2952
2953  @Override
2954  public CompletableFuture<Void> clearCompactionQueues(ServerName serverName, Set<String> queues) {
2955    return this
2956        .<Void> newAdminCaller()
2957        .action(
2958          (controller, stub) -> this
2959              .<ClearCompactionQueuesRequest, ClearCompactionQueuesResponse, Void> adminCall(
2960                controller, stub, RequestConverter.buildClearCompactionQueuesRequest(queues), (s,
2961                    c, req, done) -> s.clearCompactionQueues(controller, req, done), resp -> null))
2962        .serverName(serverName).call();
2963  }
2964
2965  @Override
2966  public CompletableFuture<List<SecurityCapability>> getSecurityCapabilities() {
2967    return this
2968        .<List<SecurityCapability>> newMasterCaller()
2969        .action(
2970          (controller, stub) -> this
2971              .<SecurityCapabilitiesRequest, SecurityCapabilitiesResponse, List<SecurityCapability>>
2972                  call(controller, stub, SecurityCapabilitiesRequest.newBuilder().build(),
2973                    (s, c, req, done) -> s.getSecurityCapabilities(c, req, done),
2974                    (resp) -> ProtobufUtil.toSecurityCapabilityList(resp.getCapabilitiesList())))
2975        .call();
2976  }
2977
2978  @Override
2979  public CompletableFuture<List<RegionMetrics>> getRegionMetrics(ServerName serverName) {
2980    return getRegionMetrics(GetRegionLoadRequest.newBuilder().build(), serverName);
2981  }
2982
2983  @Override
2984  public CompletableFuture<List<RegionMetrics>> getRegionMetrics(ServerName serverName,
2985      TableName tableName) {
2986    Preconditions.checkNotNull(tableName,
2987      "tableName is null. If you don't specify a tableName, use getRegionLoads() instead");
2988    return getRegionMetrics(RequestConverter.buildGetRegionLoadRequest(tableName), serverName);
2989  }
2990
2991  private CompletableFuture<List<RegionMetrics>> getRegionMetrics(GetRegionLoadRequest request,
2992      ServerName serverName) {
2993    return this.<List<RegionMetrics>> newAdminCaller()
2994        .action((controller, stub) -> this
2995            .<GetRegionLoadRequest, GetRegionLoadResponse, List<RegionMetrics>>
2996              adminCall(controller, stub, request, (s, c, req, done) ->
2997                s.getRegionLoad(controller, req, done), RegionMetricsBuilder::toRegionMetrics))
2998        .serverName(serverName).call();
2999  }
3000
3001  @Override
3002  public CompletableFuture<Boolean> isMasterInMaintenanceMode() {
3003    return this
3004        .<Boolean> newMasterCaller()
3005        .action(
3006          (controller, stub) -> this
3007              .<IsInMaintenanceModeRequest, IsInMaintenanceModeResponse, Boolean> call(controller,
3008                stub, IsInMaintenanceModeRequest.newBuilder().build(),
3009                (s, c, req, done) -> s.isMasterInMaintenanceMode(c, req, done),
3010                resp -> resp.getInMaintenanceMode())).call();
3011  }
3012
3013  @Override
3014  public CompletableFuture<CompactionState> getCompactionState(TableName tableName,
3015      CompactType compactType) {
3016    CompletableFuture<CompactionState> future = new CompletableFuture<>();
3017
3018    switch (compactType) {
3019      case MOB:
3020        addListener(connection.registry.getActiveMaster(), (serverName, err) -> {
3021          if (err != null) {
3022            future.completeExceptionally(err);
3023            return;
3024          }
3025          RegionInfo regionInfo = RegionInfo.createMobRegionInfo(tableName);
3026
3027          addListener(this.<GetRegionInfoResponse> newAdminCaller().serverName(serverName)
3028            .action((controller, stub) -> this
3029              .<GetRegionInfoRequest, GetRegionInfoResponse, GetRegionInfoResponse> adminCall(
3030                controller, stub,
3031                RequestConverter.buildGetRegionInfoRequest(regionInfo.getRegionName(), true),
3032                (s, c, req, done) -> s.getRegionInfo(controller, req, done), resp -> resp))
3033            .call(), (resp2, err2) -> {
3034              if (err2 != null) {
3035                future.completeExceptionally(err2);
3036              } else {
3037                if (resp2.hasCompactionState()) {
3038                  future.complete(ProtobufUtil.createCompactionState(resp2.getCompactionState()));
3039                } else {
3040                  future.complete(CompactionState.NONE);
3041                }
3042              }
3043            });
3044        });
3045        break;
3046      case NORMAL:
3047        addListener(getTableHRegionLocations(tableName), (locations, err) -> {
3048          if (err != null) {
3049            future.completeExceptionally(err);
3050            return;
3051          }
3052          ConcurrentLinkedQueue<CompactionState> regionStates = new ConcurrentLinkedQueue<>();
3053          List<CompletableFuture<CompactionState>> futures = new ArrayList<>();
3054          locations.stream().filter(loc -> loc.getServerName() != null)
3055            .filter(loc -> loc.getRegion() != null).filter(loc -> !loc.getRegion().isOffline())
3056            .map(loc -> loc.getRegion().getRegionName()).forEach(region -> {
3057              futures.add(getCompactionStateForRegion(region).whenComplete((regionState, err2) -> {
3058                // If any region compaction state is MAJOR_AND_MINOR
3059                // the table compaction state is MAJOR_AND_MINOR, too.
3060                if (err2 != null) {
3061                  future.completeExceptionally(unwrapCompletionException(err2));
3062                } else if (regionState == CompactionState.MAJOR_AND_MINOR) {
3063                  future.complete(regionState);
3064                } else {
3065                  regionStates.add(regionState);
3066                }
3067              }));
3068            });
3069          addListener(
3070            CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
3071            (ret, err3) -> {
3072              // If future not completed, check all regions's compaction state
3073              if (!future.isCompletedExceptionally() && !future.isDone()) {
3074                CompactionState state = CompactionState.NONE;
3075                for (CompactionState regionState : regionStates) {
3076                  switch (regionState) {
3077                    case MAJOR:
3078                      if (state == CompactionState.MINOR) {
3079                        future.complete(CompactionState.MAJOR_AND_MINOR);
3080                      } else {
3081                        state = CompactionState.MAJOR;
3082                      }
3083                      break;
3084                    case MINOR:
3085                      if (state == CompactionState.MAJOR) {
3086                        future.complete(CompactionState.MAJOR_AND_MINOR);
3087                      } else {
3088                        state = CompactionState.MINOR;
3089                      }
3090                      break;
3091                    case NONE:
3092                    default:
3093                  }
3094                }
3095                if (!future.isDone()) {
3096                  future.complete(state);
3097                }
3098              }
3099            });
3100        });
3101        break;
3102      default:
3103        throw new IllegalArgumentException("Unknown compactType: " + compactType);
3104    }
3105
3106    return future;
3107  }
3108
3109  @Override
3110  public CompletableFuture<CompactionState> getCompactionStateForRegion(byte[] regionName) {
3111    CompletableFuture<CompactionState> future = new CompletableFuture<>();
3112    addListener(getRegionLocation(regionName), (location, err) -> {
3113      if (err != null) {
3114        future.completeExceptionally(err);
3115        return;
3116      }
3117      ServerName serverName = location.getServerName();
3118      if (serverName == null) {
3119        future
3120          .completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
3121        return;
3122      }
3123      addListener(
3124        this.<GetRegionInfoResponse> newAdminCaller()
3125          .action((controller, stub) -> this
3126            .<GetRegionInfoRequest, GetRegionInfoResponse, GetRegionInfoResponse> adminCall(
3127              controller, stub,
3128              RequestConverter.buildGetRegionInfoRequest(location.getRegion().getRegionName(),
3129                true),
3130              (s, c, req, done) -> s.getRegionInfo(controller, req, done), resp -> resp))
3131          .serverName(serverName).call(),
3132        (resp2, err2) -> {
3133          if (err2 != null) {
3134            future.completeExceptionally(err2);
3135          } else {
3136            if (resp2.hasCompactionState()) {
3137              future.complete(ProtobufUtil.createCompactionState(resp2.getCompactionState()));
3138            } else {
3139              future.complete(CompactionState.NONE);
3140            }
3141          }
3142        });
3143    });
3144    return future;
3145  }
3146
3147  @Override
3148  public CompletableFuture<Optional<Long>> getLastMajorCompactionTimestamp(TableName tableName) {
3149    MajorCompactionTimestampRequest request =
3150        MajorCompactionTimestampRequest.newBuilder()
3151            .setTableName(ProtobufUtil.toProtoTableName(tableName)).build();
3152    return this.<Optional<Long>> newMasterCaller().action((controller, stub) ->
3153        this.<MajorCompactionTimestampRequest, MajorCompactionTimestampResponse, Optional<Long>>
3154            call(controller, stub, request, (s, c, req, done) -> s.getLastMajorCompactionTimestamp(
3155                c, req, done), ProtobufUtil::toOptionalTimestamp)).call();
3156  }
3157
3158  @Override
3159  public CompletableFuture<Optional<Long>> getLastMajorCompactionTimestampForRegion(
3160      byte[] regionName) {
3161    CompletableFuture<Optional<Long>> future = new CompletableFuture<>();
3162    // regionName may be a full region name or encoded region name, so getRegionInfo(byte[]) first
3163    addListener(getRegionInfo(regionName), (region, err) -> {
3164      if (err != null) {
3165        future.completeExceptionally(err);
3166        return;
3167      }
3168      MajorCompactionTimestampForRegionRequest.Builder builder =
3169        MajorCompactionTimestampForRegionRequest.newBuilder();
3170      builder.setRegion(
3171        RequestConverter.buildRegionSpecifier(RegionSpecifierType.REGION_NAME, regionName));
3172      addListener(this.<Optional<Long>> newMasterCaller().action((controller, stub) -> this
3173        .<MajorCompactionTimestampForRegionRequest,
3174        MajorCompactionTimestampResponse, Optional<Long>> call(
3175          controller, stub, builder.build(),
3176          (s, c, req, done) -> s.getLastMajorCompactionTimestampForRegion(c, req, done),
3177          ProtobufUtil::toOptionalTimestamp))
3178        .call(), (timestamp, err2) -> {
3179          if (err2 != null) {
3180            future.completeExceptionally(err2);
3181          } else {
3182            future.complete(timestamp);
3183          }
3184        });
3185    });
3186    return future;
3187  }
3188
3189  @Override
3190  public CompletableFuture<Map<ServerName, Boolean>> compactionSwitch(boolean switchState,
3191      List<String> serverNamesList) {
3192    CompletableFuture<Map<ServerName, Boolean>> future = new CompletableFuture<>();
3193    addListener(getRegionServerList(serverNamesList), (serverNames, err) -> {
3194      if (err != null) {
3195        future.completeExceptionally(err);
3196        return;
3197      }
3198      // Accessed by multiple threads.
3199      Map<ServerName, Boolean> serverStates = new ConcurrentHashMap<>(serverNames.size());
3200      List<CompletableFuture<Boolean>> futures = new ArrayList<>(serverNames.size());
3201      serverNames.stream().forEach(serverName -> {
3202        futures.add(switchCompact(serverName, switchState).whenComplete((serverState, err2) -> {
3203          if (err2 != null) {
3204            future.completeExceptionally(unwrapCompletionException(err2));
3205          } else {
3206            serverStates.put(serverName, serverState);
3207          }
3208        }));
3209      });
3210      addListener(
3211        CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
3212        (ret, err3) -> {
3213          if (!future.isCompletedExceptionally()) {
3214            if (err3 != null) {
3215              future.completeExceptionally(err3);
3216            } else {
3217              future.complete(serverStates);
3218            }
3219          }
3220        });
3221    });
3222    return future;
3223  }
3224
3225  private CompletableFuture<List<ServerName>> getRegionServerList(List<String> serverNamesList) {
3226    CompletableFuture<List<ServerName>> future = new CompletableFuture<>();
3227    if (serverNamesList.isEmpty()) {
3228      CompletableFuture<ClusterMetrics> clusterMetricsCompletableFuture =
3229        getClusterMetrics(EnumSet.of(Option.SERVERS_NAME));
3230      addListener(clusterMetricsCompletableFuture, (clusterMetrics, err) -> {
3231        if (err != null) {
3232          future.completeExceptionally(err);
3233        } else {
3234          future.complete(clusterMetrics.getServersName());
3235        }
3236      });
3237      return future;
3238    } else {
3239      List<ServerName> serverList = new ArrayList<>();
3240      for (String regionServerName : serverNamesList) {
3241        ServerName serverName = null;
3242        try {
3243          serverName = ServerName.valueOf(regionServerName);
3244        } catch (Exception e) {
3245          future.completeExceptionally(
3246            new IllegalArgumentException(String.format("ServerName format: %s", regionServerName)));
3247        }
3248        if (serverName == null) {
3249          future.completeExceptionally(
3250            new IllegalArgumentException(String.format("Null ServerName: %s", regionServerName)));
3251        } else {
3252          serverList.add(serverName);
3253        }
3254      }
3255      future.complete(serverList);
3256    }
3257    return future;
3258  }
3259
3260  private CompletableFuture<Boolean> switchCompact(ServerName serverName, boolean onOrOff) {
3261    return this
3262        .<Boolean>newAdminCaller()
3263        .serverName(serverName)
3264        .action((controller, stub) -> this.<CompactionSwitchRequest, CompactionSwitchResponse,
3265            Boolean>adminCall(controller, stub,
3266            CompactionSwitchRequest.newBuilder().setEnabled(onOrOff).build(), (s, c, req, done) ->
3267            s.compactionSwitch(c, req, done), resp -> resp.getPrevState())).call();
3268  }
3269
3270  @Override
3271  public CompletableFuture<Boolean> balancerSwitch(boolean on, boolean drainRITs) {
3272    return this.<Boolean> newMasterCaller()
3273      .action((controller, stub) -> this
3274        .<SetBalancerRunningRequest, SetBalancerRunningResponse, Boolean> call(controller, stub,
3275          RequestConverter.buildSetBalancerRunningRequest(on, drainRITs),
3276          (s, c, req, done) -> s.setBalancerRunning(c, req, done),
3277          (resp) -> resp.getPrevBalanceValue()))
3278      .call();
3279  }
3280
3281  @Override
3282  public CompletableFuture<BalanceResponse> balance(BalanceRequest request) {
3283    return this
3284        .<BalanceResponse> newMasterCaller()
3285        .action(
3286          (controller, stub) -> this.<MasterProtos.BalanceRequest, MasterProtos.BalanceResponse, BalanceResponse> call(controller,
3287            stub, ProtobufUtil.toBalanceRequest(request),
3288            (s, c, req, done) -> s.balance(c, req, done), (resp) -> ProtobufUtil.toBalanceResponse(resp))).call();
3289  }
3290
3291
3292  @Override
3293  public CompletableFuture<Boolean> isBalancerEnabled() {
3294    return this
3295        .<Boolean> newMasterCaller()
3296        .action((controller, stub) ->
3297              this.<IsBalancerEnabledRequest, IsBalancerEnabledResponse, Boolean> call(controller,
3298            stub, RequestConverter.buildIsBalancerEnabledRequest(), (s, c, req, done)
3299                  -> s.isBalancerEnabled(c, req, done), (resp) -> resp.getEnabled())).call();
3300  }
3301
3302  @Override
3303  public CompletableFuture<Boolean> normalizerSwitch(boolean on) {
3304    return this
3305        .<Boolean> newMasterCaller()
3306        .action(
3307          (controller, stub) -> this
3308              .<SetNormalizerRunningRequest, SetNormalizerRunningResponse, Boolean> call(
3309                controller, stub, RequestConverter.buildSetNormalizerRunningRequest(on), (s, c,
3310                    req, done) -> s.setNormalizerRunning(c, req, done), (resp) -> resp
3311                    .getPrevNormalizerValue())).call();
3312  }
3313
3314  @Override
3315  public CompletableFuture<Boolean> isNormalizerEnabled() {
3316    return this
3317        .<Boolean> newMasterCaller()
3318        .action(
3319          (controller, stub) -> this
3320              .<IsNormalizerEnabledRequest, IsNormalizerEnabledResponse, Boolean> call(controller,
3321                stub, RequestConverter.buildIsNormalizerEnabledRequest(),
3322                (s, c, req, done) -> s.isNormalizerEnabled(c, req, done),
3323                (resp) -> resp.getEnabled())).call();
3324  }
3325
3326  @Override
3327  public CompletableFuture<Boolean> normalize(NormalizeTableFilterParams ntfp) {
3328    return normalize(RequestConverter.buildNormalizeRequest(ntfp));
3329  }
3330
3331  private CompletableFuture<Boolean> normalize(NormalizeRequest request) {
3332    return this
3333      .<Boolean> newMasterCaller()
3334      .action(
3335        (controller, stub) -> this.call(
3336          controller, stub, request, MasterService.Interface::normalize,
3337          NormalizeResponse::getNormalizerRan))
3338      .call();
3339  }
3340
3341  @Override
3342  public CompletableFuture<Boolean> cleanerChoreSwitch(boolean enabled) {
3343    return this
3344        .<Boolean> newMasterCaller()
3345        .action(
3346          (controller, stub) -> this
3347              .<SetCleanerChoreRunningRequest, SetCleanerChoreRunningResponse, Boolean> call(
3348                controller, stub, RequestConverter.buildSetCleanerChoreRunningRequest(enabled), (s,
3349                    c, req, done) -> s.setCleanerChoreRunning(c, req, done), (resp) -> resp
3350                    .getPrevValue())).call();
3351  }
3352
3353  @Override
3354  public CompletableFuture<Boolean> isCleanerChoreEnabled() {
3355    return this
3356        .<Boolean> newMasterCaller()
3357        .action(
3358          (controller, stub) -> this
3359              .<IsCleanerChoreEnabledRequest, IsCleanerChoreEnabledResponse, Boolean> call(
3360                controller, stub, RequestConverter.buildIsCleanerChoreEnabledRequest(), (s, c, req,
3361                    done) -> s.isCleanerChoreEnabled(c, req, done), (resp) -> resp.getValue()))
3362        .call();
3363  }
3364
3365  @Override
3366  public CompletableFuture<Boolean> runCleanerChore() {
3367    return this
3368        .<Boolean> newMasterCaller()
3369        .action(
3370          (controller, stub) -> this
3371              .<RunCleanerChoreRequest, RunCleanerChoreResponse, Boolean> call(controller, stub,
3372                RequestConverter.buildRunCleanerChoreRequest(),
3373                (s, c, req, done) -> s.runCleanerChore(c, req, done),
3374                (resp) -> resp.getCleanerChoreRan())).call();
3375  }
3376
3377  @Override
3378  public CompletableFuture<Boolean> catalogJanitorSwitch(boolean enabled) {
3379    return this
3380        .<Boolean> newMasterCaller()
3381        .action(
3382          (controller, stub) -> this
3383              .<EnableCatalogJanitorRequest, EnableCatalogJanitorResponse, Boolean> call(
3384                controller, stub, RequestConverter.buildEnableCatalogJanitorRequest(enabled), (s,
3385                    c, req, done) -> s.enableCatalogJanitor(c, req, done), (resp) -> resp
3386                    .getPrevValue())).call();
3387  }
3388
3389  @Override
3390  public CompletableFuture<Boolean> isCatalogJanitorEnabled() {
3391    return this
3392        .<Boolean> newMasterCaller()
3393        .action(
3394          (controller, stub) -> this
3395              .<IsCatalogJanitorEnabledRequest, IsCatalogJanitorEnabledResponse, Boolean> call(
3396                controller, stub, RequestConverter.buildIsCatalogJanitorEnabledRequest(), (s, c,
3397                    req, done) -> s.isCatalogJanitorEnabled(c, req, done), (resp) -> resp
3398                    .getValue())).call();
3399  }
3400
3401  @Override
3402  public CompletableFuture<Integer> runCatalogJanitor() {
3403    return this
3404        .<Integer> newMasterCaller()
3405        .action(
3406          (controller, stub) -> this.<RunCatalogScanRequest, RunCatalogScanResponse, Integer> call(
3407            controller, stub, RequestConverter.buildCatalogScanRequest(),
3408            (s, c, req, done) -> s.runCatalogScan(c, req, done), (resp) -> resp.getScanResult()))
3409        .call();
3410  }
3411
3412  @Override
3413  public <S, R> CompletableFuture<R> coprocessorService(Function<RpcChannel, S> stubMaker,
3414      ServiceCaller<S, R> callable) {
3415    MasterCoprocessorRpcChannelImpl channel =
3416        new MasterCoprocessorRpcChannelImpl(this.<Message> newMasterCaller());
3417    S stub = stubMaker.apply(channel);
3418    CompletableFuture<R> future = new CompletableFuture<>();
3419    ClientCoprocessorRpcController controller = new ClientCoprocessorRpcController();
3420    callable.call(stub, controller, resp -> {
3421      if (controller.failed()) {
3422        future.completeExceptionally(controller.getFailed());
3423      } else {
3424        future.complete(resp);
3425      }
3426    });
3427    return future;
3428  }
3429
3430  @Override
3431  public <S, R> CompletableFuture<R> coprocessorService(Function<RpcChannel, S> stubMaker,
3432      ServiceCaller<S, R> callable, ServerName serverName) {
3433    RegionServerCoprocessorRpcChannelImpl channel =
3434        new RegionServerCoprocessorRpcChannelImpl(this.<Message> newServerCaller().serverName(
3435          serverName));
3436    S stub = stubMaker.apply(channel);
3437    CompletableFuture<R> future = new CompletableFuture<>();
3438    ClientCoprocessorRpcController controller = new ClientCoprocessorRpcController();
3439    callable.call(stub, controller, resp -> {
3440      if (controller.failed()) {
3441        future.completeExceptionally(controller.getFailed());
3442      } else {
3443        future.complete(resp);
3444      }
3445    });
3446    return future;
3447  }
3448
3449  @Override
3450  public CompletableFuture<List<ServerName>> clearDeadServers(List<ServerName> servers) {
3451    return this.<List<ServerName>> newMasterCaller()
3452      .action((controller, stub) -> this
3453        .<ClearDeadServersRequest, ClearDeadServersResponse, List<ServerName>> call(
3454          controller, stub, RequestConverter.buildClearDeadServersRequest(servers),
3455          (s, c, req, done) -> s.clearDeadServers(c, req, done),
3456          (resp) -> ProtobufUtil.toServerNameList(resp.getServerNameList())))
3457      .call();
3458  }
3459
3460  <T> ServerRequestCallerBuilder<T> newServerCaller() {
3461    return this.connection.callerFactory.<T> serverRequest()
3462      .rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
3463      .operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS)
3464      .pause(pauseNs, TimeUnit.NANOSECONDS).pauseForCQTBE(pauseForCQTBENs, TimeUnit.NANOSECONDS)
3465      .maxAttempts(maxAttempts).startLogErrorsCnt(startLogErrorsCnt);
3466  }
3467
3468  @Override
3469  public CompletableFuture<Void> enableTableReplication(TableName tableName) {
3470    if (tableName == null) {
3471      return failedFuture(new IllegalArgumentException("Table name is null"));
3472    }
3473    CompletableFuture<Void> future = new CompletableFuture<>();
3474    addListener(tableExists(tableName), (exist, err) -> {
3475      if (err != null) {
3476        future.completeExceptionally(err);
3477        return;
3478      }
3479      if (!exist) {
3480        future.completeExceptionally(new TableNotFoundException(
3481          "Table '" + tableName.getNameAsString() + "' does not exists."));
3482        return;
3483      }
3484      addListener(getTableSplits(tableName), (splits, err1) -> {
3485        if (err1 != null) {
3486          future.completeExceptionally(err1);
3487        } else {
3488          addListener(checkAndSyncTableToPeerClusters(tableName, splits), (result, err2) -> {
3489            if (err2 != null) {
3490              future.completeExceptionally(err2);
3491            } else {
3492              addListener(setTableReplication(tableName, true), (result3, err3) -> {
3493                if (err3 != null) {
3494                  future.completeExceptionally(err3);
3495                } else {
3496                  future.complete(result3);
3497                }
3498              });
3499            }
3500          });
3501        }
3502      });
3503    });
3504    return future;
3505  }
3506
3507  @Override
3508  public CompletableFuture<Void> disableTableReplication(TableName tableName) {
3509    if (tableName == null) {
3510      return failedFuture(new IllegalArgumentException("Table name is null"));
3511    }
3512    CompletableFuture<Void> future = new CompletableFuture<>();
3513    addListener(tableExists(tableName), (exist, err) -> {
3514      if (err != null) {
3515        future.completeExceptionally(err);
3516        return;
3517      }
3518      if (!exist) {
3519        future.completeExceptionally(new TableNotFoundException(
3520          "Table '" + tableName.getNameAsString() + "' does not exists."));
3521        return;
3522      }
3523      addListener(setTableReplication(tableName, false), (result, err2) -> {
3524        if (err2 != null) {
3525          future.completeExceptionally(err2);
3526        } else {
3527          future.complete(result);
3528        }
3529      });
3530    });
3531    return future;
3532  }
3533
3534  private CompletableFuture<byte[][]> getTableSplits(TableName tableName) {
3535    CompletableFuture<byte[][]> future = new CompletableFuture<>();
3536    addListener(
3537      getRegions(tableName).thenApply(regions -> regions.stream()
3538        .filter(RegionReplicaUtil::isDefaultReplica).collect(Collectors.toList())),
3539      (regions, err2) -> {
3540        if (err2 != null) {
3541          future.completeExceptionally(err2);
3542          return;
3543        }
3544        if (regions.size() == 1) {
3545          future.complete(null);
3546        } else {
3547          byte[][] splits = new byte[regions.size() - 1][];
3548          for (int i = 1; i < regions.size(); i++) {
3549            splits[i - 1] = regions.get(i).getStartKey();
3550          }
3551          future.complete(splits);
3552        }
3553      });
3554    return future;
3555  }
3556
3557  /**
3558   * Connect to peer and check the table descriptor on peer:
3559   * <ol>
3560   * <li>Create the same table on peer when not exist.</li>
3561   * <li>Throw an exception if the table already has replication enabled on any of the column
3562   * families.</li>
3563   * <li>Throw an exception if the table exists on peer cluster but descriptors are not same.</li>
3564   * </ol>
3565   * @param tableName name of the table to sync to the peer
3566   * @param splits table split keys
3567   */
3568  private CompletableFuture<Void> checkAndSyncTableToPeerClusters(TableName tableName,
3569      byte[][] splits) {
3570    CompletableFuture<Void> future = new CompletableFuture<>();
3571    addListener(listReplicationPeers(), (peers, err) -> {
3572      if (err != null) {
3573        future.completeExceptionally(err);
3574        return;
3575      }
3576      if (peers == null || peers.size() <= 0) {
3577        future.completeExceptionally(
3578          new IllegalArgumentException("Found no peer cluster for replication."));
3579        return;
3580      }
3581      List<CompletableFuture<Void>> futures = new ArrayList<>();
3582      peers.stream().filter(peer -> peer.getPeerConfig().needToReplicate(tableName))
3583        .forEach(peer -> {
3584          futures.add(trySyncTableToPeerCluster(tableName, splits, peer));
3585        });
3586      addListener(
3587        CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
3588        (result, err2) -> {
3589          if (err2 != null) {
3590            future.completeExceptionally(err2);
3591          } else {
3592            future.complete(result);
3593          }
3594        });
3595    });
3596    return future;
3597  }
3598
3599  private CompletableFuture<Void> trySyncTableToPeerCluster(TableName tableName, byte[][] splits,
3600      ReplicationPeerDescription peer) {
3601    Configuration peerConf = null;
3602    try {
3603      peerConf =
3604        ReplicationPeerConfigUtil.getPeerClusterConfiguration(connection.getConfiguration(), peer);
3605    } catch (IOException e) {
3606      return failedFuture(e);
3607    }
3608    CompletableFuture<Void> future = new CompletableFuture<>();
3609    addListener(ConnectionFactory.createAsyncConnection(peerConf), (conn, err) -> {
3610      if (err != null) {
3611        future.completeExceptionally(err);
3612        return;
3613      }
3614      addListener(getDescriptor(tableName), (tableDesc, err1) -> {
3615        if (err1 != null) {
3616          future.completeExceptionally(err1);
3617          return;
3618        }
3619        AsyncAdmin peerAdmin = conn.getAdmin();
3620        addListener(peerAdmin.tableExists(tableName), (exist, err2) -> {
3621          if (err2 != null) {
3622            future.completeExceptionally(err2);
3623            return;
3624          }
3625          if (!exist) {
3626            CompletableFuture<Void> createTableFuture = null;
3627            if (splits == null) {
3628              createTableFuture = peerAdmin.createTable(tableDesc);
3629            } else {
3630              createTableFuture = peerAdmin.createTable(tableDesc, splits);
3631            }
3632            addListener(createTableFuture, (result, err3) -> {
3633              if (err3 != null) {
3634                future.completeExceptionally(err3);
3635              } else {
3636                future.complete(result);
3637              }
3638            });
3639          } else {
3640            addListener(compareTableWithPeerCluster(tableName, tableDesc, peer, peerAdmin),
3641              (result, err4) -> {
3642                if (err4 != null) {
3643                  future.completeExceptionally(err4);
3644                } else {
3645                  future.complete(result);
3646                }
3647              });
3648          }
3649        });
3650      });
3651    });
3652    return future;
3653  }
3654
3655  private CompletableFuture<Void> compareTableWithPeerCluster(TableName tableName,
3656      TableDescriptor tableDesc, ReplicationPeerDescription peer, AsyncAdmin peerAdmin) {
3657    CompletableFuture<Void> future = new CompletableFuture<>();
3658    addListener(peerAdmin.getDescriptor(tableName), (peerTableDesc, err) -> {
3659      if (err != null) {
3660        future.completeExceptionally(err);
3661        return;
3662      }
3663      if (peerTableDesc == null) {
3664        future.completeExceptionally(
3665          new IllegalArgumentException("Failed to get table descriptor for table " +
3666            tableName.getNameAsString() + " from peer cluster " + peer.getPeerId()));
3667        return;
3668      }
3669      if (TableDescriptor.COMPARATOR_IGNORE_REPLICATION.compare(peerTableDesc, tableDesc) != 0) {
3670        future.completeExceptionally(new IllegalArgumentException(
3671          "Table " + tableName.getNameAsString() + " exists in peer cluster " + peer.getPeerId() +
3672            ", but the table descriptors are not same when compared with source cluster." +
3673            " Thus can not enable the table's replication switch."));
3674        return;
3675      }
3676      future.complete(null);
3677    });
3678    return future;
3679  }
3680
3681  /**
3682   * Set the table's replication switch if the table's replication switch is already not set.
3683   * @param tableName name of the table
3684   * @param enableRep is replication switch enable or disable
3685   */
3686  private CompletableFuture<Void> setTableReplication(TableName tableName, boolean enableRep) {
3687    CompletableFuture<Void> future = new CompletableFuture<>();
3688    addListener(getDescriptor(tableName), (tableDesc, err) -> {
3689      if (err != null) {
3690        future.completeExceptionally(err);
3691        return;
3692      }
3693      if (!tableDesc.matchReplicationScope(enableRep)) {
3694        int scope =
3695          enableRep ? HConstants.REPLICATION_SCOPE_GLOBAL : HConstants.REPLICATION_SCOPE_LOCAL;
3696        TableDescriptor newTableDesc =
3697          TableDescriptorBuilder.newBuilder(tableDesc).setReplicationScope(scope).build();
3698        addListener(modifyTable(newTableDesc), (result, err2) -> {
3699          if (err2 != null) {
3700            future.completeExceptionally(err2);
3701          } else {
3702            future.complete(result);
3703          }
3704        });
3705      } else {
3706        future.complete(null);
3707      }
3708    });
3709    return future;
3710  }
3711
3712  @Override
3713  public CompletableFuture<CacheEvictionStats> clearBlockCache(TableName tableName) {
3714    CompletableFuture<CacheEvictionStats> future = new CompletableFuture<>();
3715    addListener(getTableHRegionLocations(tableName), (locations, err) -> {
3716      if (err != null) {
3717        future.completeExceptionally(err);
3718        return;
3719      }
3720      Map<ServerName, List<RegionInfo>> regionInfoByServerName =
3721        locations.stream().filter(l -> l.getRegion() != null)
3722          .filter(l -> !l.getRegion().isOffline()).filter(l -> l.getServerName() != null)
3723          .collect(Collectors.groupingBy(l -> l.getServerName(),
3724            Collectors.mapping(l -> l.getRegion(), Collectors.toList())));
3725      List<CompletableFuture<CacheEvictionStats>> futures = new ArrayList<>();
3726      CacheEvictionStatsAggregator aggregator = new CacheEvictionStatsAggregator();
3727      for (Map.Entry<ServerName, List<RegionInfo>> entry : regionInfoByServerName.entrySet()) {
3728        futures
3729          .add(clearBlockCache(entry.getKey(), entry.getValue()).whenComplete((stats, err2) -> {
3730            if (err2 != null) {
3731              future.completeExceptionally(unwrapCompletionException(err2));
3732            } else {
3733              aggregator.append(stats);
3734            }
3735          }));
3736      }
3737      addListener(CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])),
3738        (ret, err3) -> {
3739          if (err3 != null) {
3740            future.completeExceptionally(unwrapCompletionException(err3));
3741          } else {
3742            future.complete(aggregator.sum());
3743          }
3744        });
3745    });
3746    return future;
3747  }
3748
3749  @Override
3750  public CompletableFuture<Void> cloneTableSchema(TableName tableName, TableName newTableName,
3751      boolean preserveSplits) {
3752    CompletableFuture<Void> future = new CompletableFuture<>();
3753    addListener(tableExists(tableName), (exist, err) -> {
3754      if (err != null) {
3755        future.completeExceptionally(err);
3756        return;
3757      }
3758      if (!exist) {
3759        future.completeExceptionally(new TableNotFoundException(tableName));
3760        return;
3761      }
3762      addListener(tableExists(newTableName), (exist1, err1) -> {
3763        if (err1 != null) {
3764          future.completeExceptionally(err1);
3765          return;
3766        }
3767        if (exist1) {
3768          future.completeExceptionally(new TableExistsException(newTableName));
3769          return;
3770        }
3771        addListener(getDescriptor(tableName), (tableDesc, err2) -> {
3772          if (err2 != null) {
3773            future.completeExceptionally(err2);
3774            return;
3775          }
3776          TableDescriptor newTableDesc = TableDescriptorBuilder.copy(newTableName, tableDesc);
3777          if (preserveSplits) {
3778            addListener(getTableSplits(tableName), (splits, err3) -> {
3779              if (err3 != null) {
3780                future.completeExceptionally(err3);
3781              } else {
3782                addListener(
3783                  splits != null ? createTable(newTableDesc, splits) : createTable(newTableDesc),
3784                  (result, err4) -> {
3785                    if (err4 != null) {
3786                      future.completeExceptionally(err4);
3787                    } else {
3788                      future.complete(result);
3789                    }
3790                  });
3791              }
3792            });
3793          } else {
3794            addListener(createTable(newTableDesc), (result, err5) -> {
3795              if (err5 != null) {
3796                future.completeExceptionally(err5);
3797              } else {
3798                future.complete(result);
3799              }
3800            });
3801          }
3802        });
3803      });
3804    });
3805    return future;
3806  }
3807
3808  private CompletableFuture<CacheEvictionStats> clearBlockCache(ServerName serverName,
3809      List<RegionInfo> hris) {
3810    return this.<CacheEvictionStats> newAdminCaller().action((controller, stub) -> this
3811      .<ClearRegionBlockCacheRequest, ClearRegionBlockCacheResponse, CacheEvictionStats> adminCall(
3812        controller, stub, RequestConverter.buildClearRegionBlockCacheRequest(hris),
3813        (s, c, req, done) -> s.clearRegionBlockCache(controller, req, done),
3814        resp -> ProtobufUtil.toCacheEvictionStats(resp.getStats())))
3815      .serverName(serverName).call();
3816  }
3817
3818  @Override
3819  public CompletableFuture<Boolean> switchRpcThrottle(boolean enable) {
3820    CompletableFuture<Boolean> future = this.<Boolean> newMasterCaller()
3821        .action((controller, stub) -> this
3822            .<SwitchRpcThrottleRequest, SwitchRpcThrottleResponse, Boolean> call(controller, stub,
3823              SwitchRpcThrottleRequest.newBuilder().setRpcThrottleEnabled(enable).build(),
3824              (s, c, req, done) -> s.switchRpcThrottle(c, req, done),
3825              resp -> resp.getPreviousRpcThrottleEnabled()))
3826        .call();
3827    return future;
3828  }
3829
3830  @Override
3831  public CompletableFuture<Boolean> isRpcThrottleEnabled() {
3832    CompletableFuture<Boolean> future = this.<Boolean> newMasterCaller()
3833        .action((controller, stub) -> this
3834            .<IsRpcThrottleEnabledRequest, IsRpcThrottleEnabledResponse, Boolean> call(controller,
3835              stub, IsRpcThrottleEnabledRequest.newBuilder().build(),
3836              (s, c, req, done) -> s.isRpcThrottleEnabled(c, req, done),
3837              resp -> resp.getRpcThrottleEnabled()))
3838        .call();
3839    return future;
3840  }
3841
3842  @Override
3843  public CompletableFuture<Boolean> exceedThrottleQuotaSwitch(boolean enable) {
3844    CompletableFuture<Boolean> future = this.<Boolean> newMasterCaller()
3845        .action((controller, stub) -> this
3846            .<SwitchExceedThrottleQuotaRequest, SwitchExceedThrottleQuotaResponse, Boolean> call(
3847              controller, stub,
3848              SwitchExceedThrottleQuotaRequest.newBuilder().setExceedThrottleQuotaEnabled(enable)
3849                  .build(),
3850              (s, c, req, done) -> s.switchExceedThrottleQuota(c, req, done),
3851              resp -> resp.getPreviousExceedThrottleQuotaEnabled()))
3852        .call();
3853    return future;
3854  }
3855
3856  @Override
3857  public CompletableFuture<Map<TableName, Long>> getSpaceQuotaTableSizes() {
3858    return this.<Map<TableName, Long>> newMasterCaller().action((controller, stub) -> this
3859      .<GetSpaceQuotaRegionSizesRequest, GetSpaceQuotaRegionSizesResponse,
3860      Map<TableName, Long>> call(controller, stub,
3861        RequestConverter.buildGetSpaceQuotaRegionSizesRequest(),
3862        (s, c, req, done) -> s.getSpaceQuotaRegionSizes(c, req, done),
3863        resp -> resp.getSizesList().stream().collect(Collectors
3864          .toMap(sizes -> ProtobufUtil.toTableName(sizes.getTableName()), RegionSizes::getSize))))
3865      .call();
3866  }
3867
3868  @Override
3869  public CompletableFuture<Map<TableName, SpaceQuotaSnapshot>> getRegionServerSpaceQuotaSnapshots(
3870      ServerName serverName) {
3871    return this.<Map<TableName, SpaceQuotaSnapshot>> newAdminCaller()
3872      .action((controller, stub) -> this
3873        .<GetSpaceQuotaSnapshotsRequest, GetSpaceQuotaSnapshotsResponse,
3874        Map<TableName, SpaceQuotaSnapshot>> adminCall(controller, stub,
3875          RequestConverter.buildGetSpaceQuotaSnapshotsRequest(),
3876          (s, c, req, done) -> s.getSpaceQuotaSnapshots(controller, req, done),
3877          resp -> resp.getSnapshotsList().stream()
3878            .collect(Collectors.toMap(snapshot -> ProtobufUtil.toTableName(snapshot.getTableName()),
3879              snapshot -> SpaceQuotaSnapshot.toSpaceQuotaSnapshot(snapshot.getSnapshot())))))
3880      .serverName(serverName).call();
3881  }
3882
3883  private CompletableFuture<SpaceQuotaSnapshot> getCurrentSpaceQuotaSnapshot(
3884      Converter<SpaceQuotaSnapshot, GetQuotaStatesResponse> converter) {
3885    return this.<SpaceQuotaSnapshot> newMasterCaller()
3886      .action((controller, stub) -> this
3887        .<GetQuotaStatesRequest, GetQuotaStatesResponse, SpaceQuotaSnapshot> call(controller, stub,
3888          RequestConverter.buildGetQuotaStatesRequest(),
3889          (s, c, req, done) -> s.getQuotaStates(c, req, done), converter))
3890      .call();
3891  }
3892
3893  @Override
3894  public CompletableFuture<SpaceQuotaSnapshot> getCurrentSpaceQuotaSnapshot(String namespace) {
3895    return getCurrentSpaceQuotaSnapshot(resp -> resp.getNsSnapshotsList().stream()
3896      .filter(s -> s.getNamespace().equals(namespace)).findFirst()
3897      .map(s -> SpaceQuotaSnapshot.toSpaceQuotaSnapshot(s.getSnapshot())).orElse(null));
3898  }
3899
3900  @Override
3901  public CompletableFuture<SpaceQuotaSnapshot> getCurrentSpaceQuotaSnapshot(TableName tableName) {
3902    HBaseProtos.TableName protoTableName = ProtobufUtil.toProtoTableName(tableName);
3903    return getCurrentSpaceQuotaSnapshot(resp -> resp.getTableSnapshotsList().stream()
3904      .filter(s -> s.getTableName().equals(protoTableName)).findFirst()
3905      .map(s -> SpaceQuotaSnapshot.toSpaceQuotaSnapshot(s.getSnapshot())).orElse(null));
3906  }
3907
3908  @Override
3909  public CompletableFuture<Void> grant(UserPermission userPermission,
3910      boolean mergeExistingPermissions) {
3911    return this.<Void> newMasterCaller()
3912        .action((controller, stub) -> this.<GrantRequest, GrantResponse, Void> call(controller,
3913          stub, ShadedAccessControlUtil.buildGrantRequest(userPermission, mergeExistingPermissions),
3914          (s, c, req, done) -> s.grant(c, req, done), resp -> null))
3915        .call();
3916  }
3917
3918  @Override
3919  public CompletableFuture<Void> revoke(UserPermission userPermission) {
3920    return this.<Void> newMasterCaller()
3921        .action((controller, stub) -> this.<RevokeRequest, RevokeResponse, Void> call(controller,
3922          stub, ShadedAccessControlUtil.buildRevokeRequest(userPermission),
3923          (s, c, req, done) -> s.revoke(c, req, done), resp -> null))
3924        .call();
3925  }
3926
3927  @Override
3928  public CompletableFuture<List<UserPermission>>
3929      getUserPermissions(GetUserPermissionsRequest getUserPermissionsRequest) {
3930    return this.<List<UserPermission>> newMasterCaller().action((controller,
3931        stub) -> this.<AccessControlProtos.GetUserPermissionsRequest, GetUserPermissionsResponse,
3932            List<UserPermission>> call(controller, stub,
3933              ShadedAccessControlUtil.buildGetUserPermissionsRequest(getUserPermissionsRequest),
3934              (s, c, req, done) -> s.getUserPermissions(c, req, done),
3935              resp -> resp.getUserPermissionList().stream()
3936                .map(uPerm -> ShadedAccessControlUtil.toUserPermission(uPerm))
3937                .collect(Collectors.toList())))
3938        .call();
3939  }
3940
3941  @Override
3942  public CompletableFuture<List<Boolean>> hasUserPermissions(String userName,
3943      List<Permission> permissions) {
3944    return this.<List<Boolean>> newMasterCaller()
3945        .action((controller, stub) -> this
3946            .<HasUserPermissionsRequest, HasUserPermissionsResponse, List<Boolean>> call(controller,
3947              stub, ShadedAccessControlUtil.buildHasUserPermissionsRequest(userName, permissions),
3948              (s, c, req, done) -> s.hasUserPermissions(c, req, done),
3949              resp -> resp.getHasUserPermissionList()))
3950        .call();
3951  }
3952
3953  @Override
3954  public CompletableFuture<Boolean> snapshotCleanupSwitch(final boolean on,
3955      final boolean sync) {
3956    return this.<Boolean>newMasterCaller().action((controller, stub) -> this
3957        .call(controller, stub, RequestConverter.buildSetSnapshotCleanupRequest(on, sync),
3958            MasterService.Interface::switchSnapshotCleanup,
3959            SetSnapshotCleanupResponse::getPrevSnapshotCleanup)).call();
3960  }
3961
3962  @Override
3963  public CompletableFuture<Boolean> isSnapshotCleanupEnabled() {
3964    return this.<Boolean>newMasterCaller().action((controller, stub) -> this
3965        .call(controller, stub, RequestConverter.buildIsSnapshotCleanupEnabledRequest(),
3966            MasterService.Interface::isSnapshotCleanupEnabled,
3967            IsSnapshotCleanupEnabledResponse::getEnabled)).call();
3968  }
3969
3970  @Override
3971  public CompletableFuture<Void> moveServersToRSGroup(Set<Address> servers, String groupName) {
3972    return this.<Void> newMasterCaller()
3973        .action((controller, stub) -> this.
3974            <MoveServersRequest, MoveServersResponse, Void> call(controller, stub,
3975                RequestConverter.buildMoveServersRequest(servers, groupName),
3976              (s, c, req, done) -> s.moveServers(c, req, done), resp -> null))
3977        .call();
3978  }
3979
3980  @Override
3981  public CompletableFuture<Void> addRSGroup(String groupName) {
3982    return this.<Void> newMasterCaller()
3983        .action(((controller, stub) -> this.
3984            <AddRSGroupRequest, AddRSGroupResponse, Void> call(controller, stub,
3985                AddRSGroupRequest.newBuilder().setRSGroupName(groupName).build(),
3986              (s, c, req, done) -> s.addRSGroup(c, req, done), resp -> null)))
3987        .call();
3988  }
3989
3990  @Override
3991  public CompletableFuture<Void> removeRSGroup(String groupName) {
3992    return this.<Void> newMasterCaller()
3993        .action((controller, stub) -> this.
3994            <RemoveRSGroupRequest, RemoveRSGroupResponse, Void> call(controller, stub,
3995                RemoveRSGroupRequest.newBuilder().setRSGroupName(groupName).build(),
3996              (s, c, req, done) -> s.removeRSGroup(c, req, done), resp -> null))
3997        .call();
3998  }
3999
4000  @Override
4001  public CompletableFuture<BalanceResponse> balanceRSGroup(String groupName,
4002    BalanceRequest request) {
4003    return this.<BalanceResponse>newMasterCaller().action(
4004        (controller, stub) -> this.<BalanceRSGroupRequest, BalanceRSGroupResponse, BalanceResponse>call(
4005          controller, stub, ProtobufUtil.createBalanceRSGroupRequest(groupName, request),
4006          MasterService.Interface::balanceRSGroup, ProtobufUtil::toBalanceResponse))
4007      .call();
4008  }
4009
4010  @Override
4011  public CompletableFuture<List<RSGroupInfo>> listRSGroups() {
4012    return this.<List<RSGroupInfo>> newMasterCaller()
4013        .action((controller, stub) -> this
4014            .<ListRSGroupInfosRequest, ListRSGroupInfosResponse, List<RSGroupInfo>> call(
4015                controller, stub, ListRSGroupInfosRequest.getDefaultInstance(),
4016              (s, c, req, done) -> s.listRSGroupInfos(c, req, done),
4017              resp -> resp.getRSGroupInfoList().stream()
4018                  .map(r -> ProtobufUtil.toGroupInfo(r))
4019                  .collect(Collectors.toList())))
4020        .call();
4021  }
4022
4023  private CompletableFuture<List<LogEntry>> getSlowLogResponses(
4024      final Map<String, Object> filterParams, final Set<ServerName> serverNames, final int limit,
4025      final String logType) {
4026    if (CollectionUtils.isEmpty(serverNames)) {
4027      return CompletableFuture.completedFuture(Collections.emptyList());
4028    }
4029    return CompletableFuture.supplyAsync(() -> serverNames.stream()
4030      .map((ServerName serverName) ->
4031        getSlowLogResponseFromServer(serverName, filterParams, limit, logType))
4032      .map(CompletableFuture::join)
4033      .flatMap(List::stream)
4034      .collect(Collectors.toList()));
4035  }
4036
4037  private CompletableFuture<List<LogEntry>> getSlowLogResponseFromServer(ServerName serverName,
4038      Map<String, Object> filterParams, int limit, String logType) {
4039    return this.<List<LogEntry>>newAdminCaller().action((controller, stub) -> this
4040      .adminCall(controller, stub,
4041        RequestConverter.buildSlowLogResponseRequest(filterParams, limit, logType),
4042        AdminService.Interface::getLogEntries, ProtobufUtil::toSlowLogPayloads))
4043      .serverName(serverName).call();
4044  }
4045
4046  @Override
4047  public CompletableFuture<List<Boolean>> clearSlowLogResponses(
4048      @Nullable Set<ServerName> serverNames) {
4049    if (CollectionUtils.isEmpty(serverNames)) {
4050      return CompletableFuture.completedFuture(Collections.emptyList());
4051    }
4052    List<CompletableFuture<Boolean>> clearSlowLogResponseList = serverNames.stream()
4053      .map(this::clearSlowLogsResponses)
4054      .collect(Collectors.toList());
4055    return convertToFutureOfList(clearSlowLogResponseList);
4056  }
4057
4058  private CompletableFuture<Boolean> clearSlowLogsResponses(final ServerName serverName) {
4059    return this.<Boolean>newAdminCaller()
4060      .action(((controller, stub) -> this
4061        .adminCall(
4062          controller, stub, RequestConverter.buildClearSlowLogResponseRequest(),
4063          AdminService.Interface::clearSlowLogsResponses,
4064          ProtobufUtil::toClearSlowLogPayload))
4065      ).serverName(serverName).call();
4066  }
4067
4068  private static <T> CompletableFuture<List<T>> convertToFutureOfList(
4069    List<CompletableFuture<T>> futures) {
4070    CompletableFuture<Void> allDoneFuture =
4071      CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
4072    return allDoneFuture.thenApply(v ->
4073      futures.stream()
4074        .map(CompletableFuture::join)
4075        .collect(Collectors.toList())
4076    );
4077  }
4078
4079  @Override
4080  public CompletableFuture<List<TableName>> listTablesInRSGroup(String groupName) {
4081    return this.<List<TableName>> newMasterCaller()
4082      .action((controller, stub) -> this
4083        .<ListTablesInRSGroupRequest, ListTablesInRSGroupResponse, List<TableName>> call(controller,
4084          stub, ListTablesInRSGroupRequest.newBuilder().setGroupName(groupName).build(),
4085          (s, c, req, done) -> s.listTablesInRSGroup(c, req, done), resp -> resp.getTableNameList()
4086            .stream().map(ProtobufUtil::toTableName).collect(Collectors.toList())))
4087      .call();
4088  }
4089
4090  @Override
4091  public CompletableFuture<Pair<List<String>, List<TableName>>>
4092    getConfiguredNamespacesAndTablesInRSGroup(String groupName) {
4093    return this.<Pair<List<String>, List<TableName>>> newMasterCaller()
4094      .action((controller, stub) -> this
4095        .<GetConfiguredNamespacesAndTablesInRSGroupRequest,
4096          GetConfiguredNamespacesAndTablesInRSGroupResponse,
4097          Pair<List<String>, List<TableName>>> call(controller, stub,
4098          GetConfiguredNamespacesAndTablesInRSGroupRequest.newBuilder().setGroupName(groupName)
4099            .build(),
4100            (s, c, req, done) -> s.getConfiguredNamespacesAndTablesInRSGroup(c, req, done),
4101            resp -> Pair.newPair(resp.getNamespaceList(), resp.getTableNameList().stream()
4102              .map(ProtobufUtil::toTableName).collect(Collectors.toList()))))
4103      .call();
4104  }
4105
4106  @Override
4107  public CompletableFuture<RSGroupInfo> getRSGroup(Address hostPort) {
4108    return this.<RSGroupInfo> newMasterCaller()
4109      .action(((controller, stub) -> this
4110        .<GetRSGroupInfoOfServerRequest, GetRSGroupInfoOfServerResponse, RSGroupInfo> call(
4111          controller, stub,
4112          GetRSGroupInfoOfServerRequest.newBuilder()
4113            .setServer(HBaseProtos.ServerName.newBuilder().setHostName(hostPort.getHostname())
4114              .setPort(hostPort.getPort()).build())
4115            .build(),
4116          (s, c, req, done) -> s.getRSGroupInfoOfServer(c, req, done),
4117          resp -> resp.hasRSGroupInfo() ? ProtobufUtil.toGroupInfo(resp.getRSGroupInfo()) : null)))
4118      .call();
4119  }
4120
4121  @Override
4122  public CompletableFuture<Void> removeServersFromRSGroup(Set<Address> servers) {
4123    return this.<Void> newMasterCaller()
4124      .action((controller, stub) -> this.
4125            <RemoveServersRequest, RemoveServersResponse, Void> call(controller, stub,
4126                RequestConverter.buildRemoveServersRequest(servers),
4127              (s, c, req, done) -> s.removeServers(c, req, done), resp -> null))
4128        .call();
4129  }
4130
4131  @Override
4132  public CompletableFuture<Void> setRSGroup(Set<TableName> tables, String groupName) {
4133    CompletableFuture<Void> future = new CompletableFuture<>();
4134    for (TableName tableName : tables) {
4135      addListener(tableExists(tableName), (exist, err) -> {
4136        if (err != null) {
4137          future.completeExceptionally(err);
4138          return;
4139        }
4140        if (!exist) {
4141          future.completeExceptionally(new TableNotFoundException(tableName));
4142          return;
4143        }
4144      });
4145    }
4146    addListener(listTableDescriptors(new ArrayList<>(tables)), ((tableDescriptions, err) -> {
4147      if (err != null) {
4148        future.completeExceptionally(err);
4149        return;
4150      }
4151      if (tableDescriptions == null || tableDescriptions.isEmpty()) {
4152        future.complete(null);
4153        return;
4154      }
4155      List<TableDescriptor> newTableDescriptors = new ArrayList<>();
4156      for (TableDescriptor td : tableDescriptions) {
4157        newTableDescriptors
4158            .add(TableDescriptorBuilder.newBuilder(td).setRegionServerGroup(groupName).build());
4159      }
4160      addListener(CompletableFuture.allOf(
4161        newTableDescriptors.stream().map(this::modifyTable).toArray(CompletableFuture[]::new)),
4162        (v, e) -> {
4163          if (e != null) {
4164            future.completeExceptionally(e);
4165          } else {
4166            future.complete(v);
4167          }
4168        });
4169    }));
4170    return future;
4171  }
4172
4173  @Override
4174  public CompletableFuture<RSGroupInfo> getRSGroup(TableName table) {
4175    return this.<RSGroupInfo> newMasterCaller().action(((controller, stub) -> this
4176      .<GetRSGroupInfoOfTableRequest, GetRSGroupInfoOfTableResponse, RSGroupInfo> call(controller,
4177        stub,
4178        GetRSGroupInfoOfTableRequest.newBuilder().setTableName(ProtobufUtil.toProtoTableName(table))
4179          .build(),
4180        (s, c, req, done) -> s.getRSGroupInfoOfTable(c, req, done),
4181        resp -> resp.hasRSGroupInfo() ? ProtobufUtil.toGroupInfo(resp.getRSGroupInfo()) : null)))
4182      .call();
4183  }
4184
4185  @Override
4186  public CompletableFuture<RSGroupInfo> getRSGroup(String groupName) {
4187    return this.<RSGroupInfo> newMasterCaller()
4188      .action(((controller, stub) -> this
4189        .<GetRSGroupInfoRequest, GetRSGroupInfoResponse, RSGroupInfo> call(controller, stub,
4190          GetRSGroupInfoRequest.newBuilder().setRSGroupName(groupName).build(),
4191          (s, c, req, done) -> s.getRSGroupInfo(c, req, done),
4192          resp -> resp.hasRSGroupInfo() ? ProtobufUtil.toGroupInfo(resp.getRSGroupInfo()) : null)))
4193      .call();
4194  }
4195
4196  @Override
4197  public CompletableFuture<Void> renameRSGroup(String oldName, String newName) {
4198    return this.<Void> newMasterCaller()
4199      .action(
4200        (
4201          (controller, stub) -> this.<RenameRSGroupRequest, RenameRSGroupResponse, Void> call(
4202            controller,
4203            stub,
4204            RenameRSGroupRequest.newBuilder().setOldRsgroupName(oldName).setNewRsgroupName(newName)
4205                                .build(),
4206            (s, c, req, done) -> s.renameRSGroup(c, req, done),
4207            resp -> null
4208          )
4209        )
4210      ).call();
4211  }
4212
4213  @Override
4214  public CompletableFuture<Void>
4215    updateRSGroupConfig(String groupName, Map<String, String> configuration) {
4216    UpdateRSGroupConfigRequest.Builder request = UpdateRSGroupConfigRequest.newBuilder()
4217        .setGroupName(groupName);
4218    if (configuration != null) {
4219      configuration.entrySet().forEach(e ->
4220          request.addConfiguration(NameStringPair.newBuilder().setName(e.getKey())
4221              .setValue(e.getValue()).build()));
4222    }
4223    return this.<Void> newMasterCaller()
4224        .action(((controller, stub) ->
4225            this.<UpdateRSGroupConfigRequest, UpdateRSGroupConfigResponse, Void> call(
4226                controller, stub, request.build(),
4227              (s, c, req, done) -> s.updateRSGroupConfig(c, req, done), resp -> null))
4228        ).call();
4229  }
4230
4231  private CompletableFuture<List<LogEntry>> getBalancerDecisions(final int limit) {
4232    return this.<List<LogEntry>>newMasterCaller()
4233      .action((controller, stub) ->
4234        this.call(controller, stub,
4235          ProtobufUtil.toBalancerDecisionRequest(limit),
4236          MasterService.Interface::getLogEntries, ProtobufUtil::toBalancerDecisionResponse))
4237      .call();
4238  }
4239
4240  private CompletableFuture<List<LogEntry>> getBalancerRejections(final int limit) {
4241    return this.<List<LogEntry>>newMasterCaller()
4242      .action((controller, stub) ->
4243        this.call(controller, stub,
4244          ProtobufUtil.toBalancerRejectionRequest(limit),
4245          MasterService.Interface::getLogEntries, ProtobufUtil::toBalancerRejectionResponse))
4246      .call();
4247  }
4248
4249  @Override
4250  public CompletableFuture<List<LogEntry>> getLogEntries(Set<ServerName> serverNames,
4251      String logType, ServerType serverType, int limit,
4252      Map<String, Object> filterParams) {
4253    if (logType == null || serverType == null) {
4254      throw new IllegalArgumentException("logType and/or serverType cannot be empty");
4255    }
4256    switch (logType){
4257      case "SLOW_LOG":
4258      case "LARGE_LOG":
4259        if (ServerType.MASTER.equals(serverType)) {
4260          throw new IllegalArgumentException("Slow/Large logs are not maintained by HMaster");
4261        }
4262        return getSlowLogResponses(filterParams, serverNames, limit, logType);
4263      case "BALANCER_DECISION":
4264        if (ServerType.REGION_SERVER.equals(serverType)) {
4265          throw new IllegalArgumentException(
4266            "Balancer Decision logs are not maintained by HRegionServer");
4267        }
4268        return getBalancerDecisions(limit);
4269      case "BALANCER_REJECTION":
4270        if (ServerType.REGION_SERVER.equals(serverType)) {
4271          throw new IllegalArgumentException(
4272            "Balancer Rejection logs are not maintained by HRegionServer");
4273        }
4274        return getBalancerRejections(limit);
4275      default:
4276        return CompletableFuture.completedFuture(Collections.emptyList());
4277    }
4278  }
4279
4280}