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.util; 019 020import java.io.BufferedInputStream; 021import java.io.BufferedOutputStream; 022import java.io.Closeable; 023import java.io.DataInputStream; 024import java.io.DataOutputStream; 025import java.io.File; 026import java.io.FileInputStream; 027import java.io.FileOutputStream; 028import java.io.IOException; 029import java.net.InetAddress; 030import java.nio.file.Files; 031import java.nio.file.Paths; 032import java.util.ArrayList; 033import java.util.Arrays; 034import java.util.Collection; 035import java.util.Collections; 036import java.util.EnumSet; 037import java.util.HashSet; 038import java.util.Iterator; 039import java.util.List; 040import java.util.Locale; 041import java.util.Optional; 042import java.util.Set; 043import java.util.concurrent.Callable; 044import java.util.concurrent.CancellationException; 045import java.util.concurrent.ExecutionException; 046import java.util.concurrent.ExecutorService; 047import java.util.concurrent.Executors; 048import java.util.concurrent.Future; 049import java.util.concurrent.TimeUnit; 050import java.util.concurrent.TimeoutException; 051import java.util.function.Predicate; 052import org.apache.commons.io.IOUtils; 053import org.apache.hadoop.conf.Configuration; 054import org.apache.hadoop.hbase.ClusterMetrics.Option; 055import org.apache.hadoop.hbase.HBaseConfiguration; 056import org.apache.hadoop.hbase.HConstants; 057import org.apache.hadoop.hbase.HRegionLocation; 058import org.apache.hadoop.hbase.MetaTableAccessor; 059import org.apache.hadoop.hbase.ServerName; 060import org.apache.hadoop.hbase.TableName; 061import org.apache.hadoop.hbase.UnknownRegionException; 062import org.apache.hadoop.hbase.client.Admin; 063import org.apache.hadoop.hbase.client.Connection; 064import org.apache.hadoop.hbase.client.ConnectionFactory; 065import org.apache.hadoop.hbase.client.DoNotRetryRegionException; 066import org.apache.hadoop.hbase.client.RegionInfo; 067import org.apache.hadoop.hbase.client.RegionInfoBuilder; 068import org.apache.hadoop.hbase.client.Result; 069import org.apache.hadoop.hbase.master.RackManager; 070import org.apache.hadoop.hbase.master.assignment.AssignmentManager; 071import org.apache.hadoop.hbase.net.Address; 072import org.apache.hadoop.hbase.rsgroup.RSGroupInfo; 073import org.apache.yetus.audience.InterfaceAudience; 074import org.slf4j.Logger; 075import org.slf4j.LoggerFactory; 076 077import org.apache.hbase.thirdparty.com.google.common.net.InetAddresses; 078import org.apache.hbase.thirdparty.org.apache.commons.cli.CommandLine; 079import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils; 080 081/** 082 * Tool for loading/unloading regions to/from given regionserver This tool can be run from Command 083 * line directly as a utility. Supports Ack/No Ack mode for loading/unloading operations.Ack mode 084 * acknowledges if regions are online after movement while noAck mode is best effort mode that 085 * improves performance but will still move on if region is stuck/not moved. Motivation behind noAck 086 * mode being RS shutdown where even if a Region is stuck, upon shutdown master will move it 087 * anyways. This can also be used by constructiong an Object using the builder and then calling 088 * {@link #load()} or {@link #unload()} methods for the desired operations. 089 */ 090@InterfaceAudience.Public 091public class RegionMover extends AbstractHBaseTool implements Closeable { 092 public static final String MOVE_RETRIES_MAX_KEY = "hbase.move.retries.max"; 093 public static final String MOVE_WAIT_MAX_KEY = "hbase.move.wait.max"; 094 public static final String SERVERSTART_WAIT_MAX_KEY = "hbase.serverstart.wait.max"; 095 public static final int DEFAULT_MOVE_RETRIES_MAX = 5; 096 public static final int DEFAULT_MOVE_WAIT_MAX = 60; 097 public static final int DEFAULT_SERVERSTART_WAIT_MAX = 180; 098 099 private static final Logger LOG = LoggerFactory.getLogger(RegionMover.class); 100 101 private RegionMoverBuilder rmbuilder; 102 private boolean ack = true; 103 private int maxthreads = 1; 104 private int timeout; 105 private List<String> isolateRegionIdArray; 106 private String loadUnload; 107 private String hostname; 108 private String filename; 109 private String excludeFile; 110 private String designatedFile; 111 private int port; 112 private Connection conn; 113 private Admin admin; 114 private RackManager rackManager; 115 116 private RegionMover(RegionMoverBuilder builder) throws IOException { 117 this.hostname = builder.hostname; 118 this.filename = builder.filename; 119 this.excludeFile = builder.excludeFile; 120 this.designatedFile = builder.designatedFile; 121 this.maxthreads = builder.maxthreads; 122 this.isolateRegionIdArray = builder.isolateRegionIdArray; 123 this.ack = builder.ack; 124 this.port = builder.port; 125 this.timeout = builder.timeout; 126 setConf(builder.conf); 127 this.conn = ConnectionFactory.createConnection(conf); 128 this.admin = conn.getAdmin(); 129 130 // if the hostname of master is ip, it indicates that the master/RS has enabled use-ip, we need 131 // to resolve the current hostname to ip to ensure that the RegionMover logic can be executed 132 // normally, see HBASE-27304 for details. 133 ServerName master = admin.getClusterMetrics(EnumSet.of(Option.MASTER)).getMasterName(); 134 if (InetAddresses.isInetAddress(master.getHostname())) { 135 if (!InetAddresses.isInetAddress(this.hostname)) { 136 this.hostname = InetAddress.getByName(this.hostname).getHostAddress(); 137 } 138 } 139 140 // Only while running unit tests, builder.rackManager will not be null for the convenience of 141 // providing custom rackManager. Otherwise for regular workflow/user triggered action, 142 // builder.rackManager is supposed to be null. Hence, setter of builder.rackManager is 143 // provided as @InterfaceAudience.Private and it is commented that this is just 144 // to be used by unit test. 145 rackManager = builder.rackManager == null ? new RackManager(conf) : builder.rackManager; 146 } 147 148 private RegionMover() { 149 } 150 151 @Override 152 public void close() { 153 IOUtils.closeQuietly(this.admin, e -> LOG.warn("failed to close admin", e)); 154 IOUtils.closeQuietly(this.conn, e -> LOG.warn("failed to close conn", e)); 155 } 156 157 /** 158 * Builder for Region mover. Use the {@link #build()} method to create RegionMover object. Has 159 * {@link #filename(String)}, {@link #excludeFile(String)}, {@link #maxthreads(int)}, 160 * {@link #ack(boolean)}, {@link #timeout(int)}, {@link #designatedFile(String)} methods to set 161 * the corresponding options. 162 */ 163 public static class RegionMoverBuilder { 164 private boolean ack = true; 165 private int maxthreads = 1; 166 private int timeout = Integer.MAX_VALUE; 167 private List<String> isolateRegionIdArray = new ArrayList<>(); 168 private String hostname; 169 private String filename; 170 private String excludeFile = null; 171 private String designatedFile = null; 172 private String defaultDir = System.getProperty("java.io.tmpdir"); 173 @InterfaceAudience.Private 174 final int port; 175 private final Configuration conf; 176 private RackManager rackManager; 177 178 public RegionMoverBuilder(String hostname) { 179 this(hostname, createConf()); 180 } 181 182 /** 183 * Creates a new configuration and sets region mover specific overrides 184 */ 185 private static Configuration createConf() { 186 final Configuration conf = HBaseConfiguration.create(); 187 return overrideConf(conf); 188 } 189 190 private static Configuration overrideConf(Configuration conf) { 191 conf.setInt("hbase.client.prefetch.limit", 1); 192 conf.setInt("hbase.client.pause", 500); 193 conf.setInt("hbase.client.retries.number", 100); 194 return conf; 195 } 196 197 /** 198 * @param hostname Hostname to unload regions from or load regions to. Can be either hostname or 199 * hostname:port. 200 * @param conf Configuration object 201 */ 202 public RegionMoverBuilder(String hostname, Configuration conf) { 203 String[] splitHostname = hostname.toLowerCase().split(":"); 204 this.hostname = splitHostname[0]; 205 if (splitHostname.length == 2) { 206 this.port = Integer.parseInt(splitHostname[1]); 207 } else { 208 this.port = conf.getInt(HConstants.REGIONSERVER_PORT, HConstants.DEFAULT_REGIONSERVER_PORT); 209 } 210 this.filename = defaultDir + File.separator + System.getProperty("user.name") + this.hostname 211 + ":" + Integer.toString(this.port); 212 this.conf = overrideConf(new Configuration(conf)); 213 } 214 215 /** 216 * Path of file where regions will be written to during unloading/read from during loading 217 * @return RegionMoverBuilder object 218 */ 219 public RegionMoverBuilder filename(String filename) { 220 this.filename = filename; 221 return this; 222 } 223 224 /** 225 * Set the max number of threads that will be used to move regions 226 */ 227 public RegionMoverBuilder maxthreads(int threads) { 228 this.maxthreads = threads; 229 return this; 230 } 231 232 /** 233 * Set the region ID to isolate on the region server. 234 */ 235 public RegionMoverBuilder isolateRegionIdArray(List<String> isolateRegionIdArray) { 236 this.isolateRegionIdArray = isolateRegionIdArray; 237 return this; 238 } 239 240 /** 241 * Path of file containing hostnames to be excluded during region movement. Exclude file should 242 * have 'host:port' per line. Port is mandatory here as we can have many RS running on a single 243 * host. 244 */ 245 public RegionMoverBuilder excludeFile(String excludefile) { 246 this.excludeFile = excludefile; 247 return this; 248 } 249 250 /** 251 * Set the designated file. Designated file contains hostnames where region moves. Designated 252 * file should have 'host:port' per line. Port is mandatory here as we can have many RS running 253 * on a single host. 254 * @param designatedFile The designated file 255 * @return RegionMoverBuilder object 256 */ 257 public RegionMoverBuilder designatedFile(String designatedFile) { 258 this.designatedFile = designatedFile; 259 return this; 260 } 261 262 /** 263 * Set ack/noAck mode. 264 * <p> 265 * In ack mode regions are acknowledged before and after moving and the move is retried 266 * hbase.move.retries.max times, if unsuccessful we quit with exit code 1.No Ack mode is a best 267 * effort mode,each region movement is tried once.This can be used during graceful shutdown as 268 * even if we have a stuck region,upon shutdown it'll be reassigned anyway. 269 * <p> 270 * @return RegionMoverBuilder object 271 */ 272 public RegionMoverBuilder ack(boolean ack) { 273 this.ack = ack; 274 return this; 275 } 276 277 /** 278 * Set the timeout for Load/Unload operation in seconds.This is a global timeout,threadpool for 279 * movers also have a separate time which is hbase.move.wait.max * number of regions to 280 * load/unload 281 * @param timeout in seconds 282 * @return RegionMoverBuilder object 283 */ 284 public RegionMoverBuilder timeout(int timeout) { 285 this.timeout = timeout; 286 return this; 287 } 288 289 /** 290 * Set specific rackManager implementation. This setter method is for testing purpose only. 291 * @param rackManager rackManager impl 292 * @return RegionMoverBuilder object 293 */ 294 @InterfaceAudience.Private 295 public RegionMoverBuilder rackManager(RackManager rackManager) { 296 this.rackManager = rackManager; 297 return this; 298 } 299 300 /** 301 * This method builds the appropriate RegionMover object which can then be used to load/unload 302 * using load and unload methods 303 * @return RegionMover object 304 */ 305 public RegionMover build() throws IOException { 306 return new RegionMover(this); 307 } 308 } 309 310 /** 311 * Loads the specified {@link #hostname} with regions listed in the {@link #filename} RegionMover 312 * Object has to be created using {@link #RegionMover(RegionMoverBuilder)} 313 * @return true if loading succeeded, false otherwise 314 */ 315 public boolean load() throws ExecutionException, InterruptedException, TimeoutException { 316 ExecutorService loadPool = Executors.newFixedThreadPool(1); 317 Future<Boolean> loadTask = loadPool.submit(getMetaRegionMovePlan()); 318 boolean isMetaMoved = waitTaskToFinish(loadPool, loadTask, "loading"); 319 if (!isMetaMoved) { 320 return false; 321 } 322 loadPool = Executors.newFixedThreadPool(1); 323 loadTask = loadPool.submit(getNonMetaRegionsMovePlan()); 324 return waitTaskToFinish(loadPool, loadTask, "loading"); 325 } 326 327 private Callable<Boolean> getMetaRegionMovePlan() { 328 return getRegionsMovePlan(true); 329 } 330 331 private Callable<Boolean> getNonMetaRegionsMovePlan() { 332 return getRegionsMovePlan(false); 333 } 334 335 private Callable<Boolean> getRegionsMovePlan(boolean moveMetaRegion) { 336 return () -> { 337 try { 338 List<RegionInfo> regionsToMove = readRegionsFromFile(filename); 339 if (regionsToMove.isEmpty()) { 340 LOG.info("No regions to load.Exiting"); 341 return true; 342 } 343 Optional<RegionInfo> metaRegion = getMetaRegionInfoIfToBeMoved(regionsToMove); 344 if (moveMetaRegion) { 345 if (metaRegion.isPresent()) { 346 loadRegions(Collections.singletonList(metaRegion.get())); 347 } 348 } else { 349 metaRegion.ifPresent(regionsToMove::remove); 350 loadRegions(regionsToMove); 351 } 352 } catch (Exception e) { 353 LOG.error("Error while loading regions to " + hostname, e); 354 return false; 355 } 356 return true; 357 }; 358 } 359 360 private Optional<RegionInfo> getMetaRegionInfoIfToBeMoved(List<RegionInfo> regionsToMove) { 361 return regionsToMove.stream().filter(RegionInfo::isMetaRegion).findFirst(); 362 } 363 364 private void loadRegions(List<RegionInfo> regionsToMove) throws Exception { 365 ServerName server = getTargetServer(); 366 List<RegionInfo> movedRegions = Collections.synchronizedList(new ArrayList<>()); 367 LOG.info("Moving " + regionsToMove.size() + " regions to " + server + " using " 368 + this.maxthreads + " threads.Ack mode:" + this.ack); 369 370 final ExecutorService moveRegionsPool = Executors.newFixedThreadPool(this.maxthreads); 371 List<Future<Boolean>> taskList = new ArrayList<>(); 372 int counter = 0; 373 while (counter < regionsToMove.size()) { 374 RegionInfo region = regionsToMove.get(counter); 375 ServerName currentServer = MoveWithAck.getServerNameForRegion(region, admin, conn); 376 if (currentServer == null) { 377 LOG 378 .warn("Could not get server for Region:" + region.getRegionNameAsString() + " moving on"); 379 counter++; 380 continue; 381 } else if (server.equals(currentServer)) { 382 LOG.info( 383 "Region " + region.getRegionNameAsString() + " is already on target server=" + server); 384 counter++; 385 continue; 386 } 387 if (ack) { 388 Future<Boolean> task = moveRegionsPool 389 .submit(new MoveWithAck(conn, region, currentServer, server, movedRegions)); 390 taskList.add(task); 391 } else { 392 Future<Boolean> task = moveRegionsPool 393 .submit(new MoveWithoutAck(admin, region, currentServer, server, movedRegions)); 394 taskList.add(task); 395 } 396 counter++; 397 } 398 399 moveRegionsPool.shutdown(); 400 long timeoutInSeconds = regionsToMove.size() 401 * admin.getConfiguration().getLong(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX); 402 waitMoveTasksToFinish(moveRegionsPool, taskList, timeoutInSeconds); 403 } 404 405 /** 406 * Unload regions from given {@link #hostname} using ack/noAck mode and {@link #maxthreads}.In 407 * noAck mode we do not make sure that region is successfully online on the target region 408 * server,hence it is best effort.We do not unload regions to hostnames given in 409 * {@link #excludeFile}. If designatedFile is present with some contents, we will unload regions 410 * to hostnames provided in {@link #designatedFile} 411 * @return true if unloading succeeded, false otherwise 412 */ 413 public boolean unload() throws InterruptedException, ExecutionException, TimeoutException { 414 return unloadRegions(false); 415 } 416 417 /** 418 * Unload regions from given {@link #hostname} using ack/noAck mode and {@link #maxthreads}.In 419 * noAck mode we do not make sure that region is successfully online on the target region 420 * server,hence it is best effort.We do not unload regions to hostnames given in 421 * {@link #excludeFile}. If designatedFile is present with some contents, we will unload regions 422 * to hostnames provided in {@link #designatedFile}. While unloading regions, destination 423 * RegionServers are selected from different rack i.e regions should not move to any RegionServers 424 * that belong to same rack as source RegionServer. 425 * @return true if unloading succeeded, false otherwise 426 */ 427 public boolean unloadFromRack() 428 throws InterruptedException, ExecutionException, TimeoutException { 429 return unloadRegions(true); 430 } 431 432 private boolean unloadRegions(boolean unloadFromRack) 433 throws ExecutionException, InterruptedException, TimeoutException { 434 return unloadRegions(unloadFromRack, null); 435 } 436 437 /** 438 * Isolated regions specified in {@link #isolateRegionIdArray} on {@link #hostname} in ack Mode 439 * and Unload regions from given {@link #hostname} using ack/noAck mode and {@link #maxthreads}. 440 * In noAck mode we do not make sure that region is successfully online on the target region 441 * server,hence it is the best effort. We do not unload regions to hostnames given in 442 * {@link #excludeFile}. If designatedFile is present with some contents, we will unload regions 443 * to hostnames provided in {@link #designatedFile} 444 * @return true if region isolation succeeded, false otherwise 445 */ 446 public boolean isolateRegions() 447 throws ExecutionException, InterruptedException, TimeoutException { 448 return unloadRegions(false, isolateRegionIdArray); 449 } 450 451 private boolean unloadRegions(boolean unloadFromRack, List<String> isolateRegionIdArray) 452 throws InterruptedException, ExecutionException, TimeoutException { 453 deleteFile(this.filename); 454 ExecutorService unloadPool = Executors.newFixedThreadPool(1); 455 Future<Boolean> unloadTask = unloadPool.submit(() -> { 456 List<RegionInfo> movedRegions = Collections.synchronizedList(new ArrayList<>()); 457 try { 458 // Get Online RegionServers 459 List<ServerName> regionServers = new ArrayList<>(); 460 RSGroupInfo rsgroup = admin.getRSGroup(Address.fromParts(hostname, port)); 461 LOG.info("{} belongs to {}", hostname, rsgroup.getName()); 462 regionServers.addAll(filterRSGroupServers(rsgroup, admin.getRegionServers())); 463 // Remove the host Region server from target Region Servers list 464 ServerName server = stripServer(regionServers, hostname, port); 465 if (server == null) { 466 LOG.info("Could not find server '{}:{}' in the set of region servers. giving up.", 467 hostname, port); 468 LOG.debug("List of region servers: {}", regionServers); 469 return false; 470 } 471 // Remove RS not present in the designated file 472 includeExcludeRegionServers(designatedFile, regionServers, true); 473 474 // Remove RS present in the exclude file 475 includeExcludeRegionServers(excludeFile, regionServers, false); 476 477 if (unloadFromRack) { 478 // remove regionServers that belong to same rack (as source host) since the goal is to 479 // unload regions from source regionServer to destination regionServers 480 // that belong to different rack only. 481 String sourceRack = rackManager.getRack(server); 482 List<String> racks = rackManager.getRack(regionServers); 483 Iterator<ServerName> iterator = regionServers.iterator(); 484 int i = 0; 485 while (iterator.hasNext()) { 486 iterator.next(); 487 if (racks.size() > i && racks.get(i) != null && racks.get(i).equals(sourceRack)) { 488 iterator.remove(); 489 } 490 i++; 491 } 492 } 493 494 // Remove decommissioned RS 495 Set<ServerName> decommissionedRS = new HashSet<>(admin.listDecommissionedRegionServers()); 496 if (CollectionUtils.isNotEmpty(decommissionedRS)) { 497 regionServers.removeIf(decommissionedRS::contains); 498 LOG.debug("Excluded RegionServers from unloading regions to because they " 499 + "are marked as decommissioned. Servers: {}", decommissionedRS); 500 } 501 502 stripMaster(regionServers); 503 if (regionServers.isEmpty()) { 504 LOG.warn("No Regions were moved - no servers available"); 505 return false; 506 } else { 507 LOG.info("Available servers {}", regionServers); 508 } 509 unloadRegions(server, regionServers, movedRegions, isolateRegionIdArray); 510 } catch (Exception e) { 511 LOG.error("Error while unloading regions ", e); 512 return false; 513 } finally { 514 if (movedRegions != null) { 515 writeFile(filename, movedRegions); 516 } 517 } 518 return true; 519 }); 520 return waitTaskToFinish(unloadPool, unloadTask, "unloading"); 521 } 522 523 @InterfaceAudience.Private 524 Collection<ServerName> filterRSGroupServers(RSGroupInfo rsgroup, 525 Collection<ServerName> onlineServers) { 526 List<ServerName> serverLists = new ArrayList<>(rsgroup.getServers().size()); 527 for (ServerName server : onlineServers) { 528 Address address = Address.fromParts(server.getHostname(), server.getPort()); 529 if (rsgroup.containsServer(address)) { 530 serverLists.add(server); 531 } 532 } 533 return serverLists; 534 } 535 536 private void unloadRegions(ServerName server, List<ServerName> regionServers, 537 List<RegionInfo> movedRegions, List<String> isolateRegionIdArray) throws Exception { 538 while (true) { 539 List<RegionInfo> isolateRegionInfoList = Collections.synchronizedList(new ArrayList<>()); 540 RegionInfo isolateRegionInfo = null; 541 if (isolateRegionIdArray != null && !isolateRegionIdArray.isEmpty()) { 542 // Region will be moved to target region server with Ack mode. 543 final ExecutorService isolateRegionPool = Executors.newFixedThreadPool(maxthreads); 544 List<Future<Boolean>> isolateRegionTaskList = new ArrayList<>(); 545 List<RegionInfo> recentlyIsolatedRegion = Collections.synchronizedList(new ArrayList<>()); 546 boolean allRegionOpsSuccessful = true; 547 boolean isMetaIsolated = false; 548 RegionInfo metaRegionInfo = RegionInfoBuilder.FIRST_META_REGIONINFO; 549 List<HRegionLocation> hRegionLocationRegionIsolation = 550 Collections.synchronizedList(new ArrayList<>()); 551 for (String isolateRegionId : isolateRegionIdArray) { 552 if (isolateRegionId.equalsIgnoreCase(metaRegionInfo.getEncodedName())) { 553 isMetaIsolated = true; 554 continue; 555 } 556 Result result = MetaTableAccessor.scanByRegionEncodedName(conn, isolateRegionId); 557 HRegionLocation hRegionLocation = 558 MetaTableAccessor.getRegionLocation(conn, result.getRow()); 559 if (hRegionLocation != null) { 560 hRegionLocationRegionIsolation.add(hRegionLocation); 561 } else { 562 LOG.error("Region " + isolateRegionId + " doesn't exists/can't fetch from" 563 + " meta...Quitting now"); 564 // We only move the regions if all the regions were found. 565 allRegionOpsSuccessful = false; 566 break; 567 } 568 } 569 570 if (!allRegionOpsSuccessful) { 571 break; 572 } 573 // If hbase:meta region was isolated, then it needs to be part of isolateRegionInfoList. 574 if (isMetaIsolated) { 575 List<HRegionLocation> result = 576 conn.getRegionLocator(TableName.META_TABLE_NAME).getAllRegionLocations(); 577 ServerName metaSeverName = result.get(0).getServerName(); 578 // For isolating hbase:meta, it should move explicitly in Ack mode, 579 // hence the forceMoveRegionByAck = true. 580 if (!metaSeverName.equals(server)) { 581 LOG.info("Region of {} {} is on server {} moving to {}", TableName.META_TABLE_NAME, 582 metaRegionInfo.getEncodedName(), metaSeverName, server); 583 submitRegionMovesWhileUnloading(metaSeverName, Collections.singletonList(server), 584 movedRegions, Collections.singletonList(metaRegionInfo), true); 585 } else { 586 LOG.info("Region of {} {} already exists on server: {}", TableName.META_TABLE_NAME, 587 metaRegionInfo.getEncodedName(), server); 588 } 589 isolateRegionInfoList.add(RegionInfoBuilder.FIRST_META_REGIONINFO); 590 } 591 592 if (!hRegionLocationRegionIsolation.isEmpty()) { 593 for (HRegionLocation hRegionLocation : hRegionLocationRegionIsolation) { 594 isolateRegionInfo = hRegionLocation.getRegion(); 595 isolateRegionInfoList.add(isolateRegionInfo); 596 if (hRegionLocation.getServerName() == server) { 597 LOG.info("Region {} already exists on server: {}", 598 hRegionLocation.getRegion().getEncodedName(), server); 599 } else { 600 Future<Boolean> isolateRegionTask = 601 isolateRegionPool.submit(new MoveWithAck(conn, isolateRegionInfo, 602 hRegionLocation.getServerName(), server, recentlyIsolatedRegion)); 603 isolateRegionTaskList.add(isolateRegionTask); 604 } 605 } 606 } 607 608 if (!isolateRegionTaskList.isEmpty()) { 609 isolateRegionPool.shutdown(); 610 // Now that we have fetched all the region's regionInfo, we can move them. 611 waitMoveTasksToFinish(isolateRegionPool, isolateRegionTaskList, 612 admin.getConfiguration().getLong(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX)); 613 614 Set<RegionInfo> currentRegionsOnTheServer = new HashSet<>(admin.getRegions(server)); 615 if (!currentRegionsOnTheServer.containsAll(isolateRegionInfoList)) { 616 // If all the regions are not online on the target server, 617 // we don't put RS in decommission mode and exit from here. 618 LOG.error("One of the Region move failed OR stuck in transition...Quitting now"); 619 break; 620 } 621 } else { 622 LOG.info("All regions already exists on server: {}", server); 623 } 624 // Once region has been moved to target RS, put the target RS into decommission mode, 625 // so master doesn't assign new region to the target RS while we unload the target RS. 626 // Also pass 'offload' flag as false since we don't want master to offload the target RS. 627 List<ServerName> listOfServer = new ArrayList<>(); 628 listOfServer.add(server); 629 LOG.info("Putting server: {} in decommission/draining mode", server); 630 admin.decommissionRegionServers(listOfServer, false); 631 } 632 List<RegionInfo> regionsToMove = admin.getRegions(server); 633 // Remove all the regions from the online Region list, that we just isolated. 634 // This will also include hbase:meta if it was isolated. 635 regionsToMove.removeAll(isolateRegionInfoList); 636 regionsToMove.removeAll(movedRegions); 637 if (regionsToMove.isEmpty()) { 638 LOG.info("No Regions to move....Quitting now"); 639 break; 640 } 641 LOG.info("Moving {} regions from {} to {} servers using {} threads .Ack Mode: {}", 642 regionsToMove.size(), server, regionServers.size(), this.maxthreads, ack); 643 644 Optional<RegionInfo> metaRegion = getMetaRegionInfoIfToBeMoved(regionsToMove); 645 if (metaRegion.isPresent()) { 646 RegionInfo meta = metaRegion.get(); 647 // hbase:meta should move explicitly in Ack mode. 648 submitRegionMovesWhileUnloading(server, regionServers, movedRegions, 649 Collections.singletonList(meta), true); 650 regionsToMove.remove(meta); 651 } 652 submitRegionMovesWhileUnloading(server, regionServers, movedRegions, regionsToMove, false); 653 } 654 } 655 656 private void submitRegionMovesWhileUnloading(ServerName server, List<ServerName> regionServers, 657 List<RegionInfo> movedRegions, List<RegionInfo> regionsToMove, boolean forceMoveRegionByAck) 658 throws Exception { 659 final ExecutorService moveRegionsPool = Executors.newFixedThreadPool(this.maxthreads); 660 List<Future<Boolean>> taskList = new ArrayList<>(); 661 int serverIndex = 0; 662 for (RegionInfo regionToMove : regionsToMove) { 663 // To move/isolate hbase:meta on a server, it should happen explicitly by Ack mode, hence the 664 // forceMoveRegionByAck = true. 665 if (ack || forceMoveRegionByAck) { 666 Future<Boolean> task = moveRegionsPool.submit(new MoveWithAck(conn, regionToMove, server, 667 regionServers.get(serverIndex), movedRegions)); 668 taskList.add(task); 669 } else { 670 Future<Boolean> task = moveRegionsPool.submit(new MoveWithoutAck(admin, regionToMove, 671 server, regionServers.get(serverIndex), movedRegions)); 672 taskList.add(task); 673 } 674 serverIndex = (serverIndex + 1) % regionServers.size(); 675 } 676 moveRegionsPool.shutdown(); 677 long timeoutInSeconds = regionsToMove.size() 678 * admin.getConfiguration().getLong(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX); 679 waitMoveTasksToFinish(moveRegionsPool, taskList, timeoutInSeconds); 680 } 681 682 private boolean waitTaskToFinish(ExecutorService pool, Future<Boolean> task, String operation) 683 throws TimeoutException, InterruptedException, ExecutionException { 684 pool.shutdown(); 685 try { 686 if (!pool.awaitTermination((long) this.timeout, TimeUnit.SECONDS)) { 687 LOG.warn("Timed out before finishing the " + operation + " operation. Timeout: " 688 + this.timeout + "sec"); 689 pool.shutdownNow(); 690 } 691 } catch (InterruptedException e) { 692 pool.shutdownNow(); 693 Thread.currentThread().interrupt(); 694 } 695 try { 696 return task.get(5, TimeUnit.SECONDS); 697 } catch (InterruptedException e) { 698 LOG.warn("Interrupted while {} regions on {}:{}", operation, this.hostname, this.port, e); 699 throw e; 700 } catch (ExecutionException e) { 701 LOG.error("Error while {} regions on RegionServer {}:{}", operation, this.hostname, this.port, 702 e); 703 throw e; 704 } 705 } 706 707 private void waitMoveTasksToFinish(ExecutorService moveRegionsPool, 708 List<Future<Boolean>> taskList, long timeoutInSeconds) throws Exception { 709 try { 710 if (!moveRegionsPool.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS)) { 711 moveRegionsPool.shutdownNow(); 712 } 713 } catch (InterruptedException e) { 714 moveRegionsPool.shutdownNow(); 715 Thread.currentThread().interrupt(); 716 } 717 for (Future<Boolean> future : taskList) { 718 try { 719 // if even after shutdownNow threads are stuck we wait for 5 secs max 720 if (!future.get(5, TimeUnit.SECONDS)) { 721 LOG.error("Was Not able to move region....Exiting Now"); 722 throw new Exception("Could not move region Exception"); 723 } 724 } catch (InterruptedException e) { 725 LOG.error("Interrupted while waiting for Thread to Complete " + e.getMessage(), e); 726 throw e; 727 } catch (ExecutionException e) { 728 boolean ignoreFailure = ignoreRegionMoveFailure(e); 729 if (ignoreFailure) { 730 LOG.debug("Ignore region move failure, it might have been split/merged.", e); 731 } else { 732 LOG.error("Got Exception From Thread While moving region {}", e.getMessage(), e); 733 throw e; 734 } 735 } catch (CancellationException e) { 736 LOG.error("Thread for moving region cancelled. Timeout for cancellation:" + timeoutInSeconds 737 + "secs", e); 738 throw e; 739 } 740 } 741 } 742 743 private boolean ignoreRegionMoveFailure(ExecutionException e) { 744 boolean ignoreFailure = false; 745 if (e.getCause() instanceof UnknownRegionException) { 746 // region does not exist anymore 747 ignoreFailure = true; 748 } else if ( 749 e.getCause() instanceof DoNotRetryRegionException && e.getCause().getMessage() != null 750 && e.getCause().getMessage() 751 .contains(AssignmentManager.UNEXPECTED_STATE_REGION + "state=SPLIT,") 752 ) { 753 // region is recently split 754 ignoreFailure = true; 755 } 756 return ignoreFailure; 757 } 758 759 private ServerName getTargetServer() throws Exception { 760 ServerName server = null; 761 int maxWaitInSeconds = 762 admin.getConfiguration().getInt(SERVERSTART_WAIT_MAX_KEY, DEFAULT_SERVERSTART_WAIT_MAX); 763 long maxWait = EnvironmentEdgeManager.currentTime() + maxWaitInSeconds * 1000; 764 while (EnvironmentEdgeManager.currentTime() < maxWait) { 765 try { 766 List<ServerName> regionServers = new ArrayList<>(); 767 regionServers.addAll(admin.getRegionServers()); 768 // Remove the host Region server from target Region Servers list 769 server = stripServer(regionServers, hostname, port); 770 if (server != null) { 771 break; 772 } else { 773 LOG.warn("Server " + hostname + ":" + port + " is not up yet, waiting"); 774 } 775 } catch (IOException e) { 776 LOG.warn("Could not get list of region servers", e); 777 } 778 Thread.sleep(500); 779 } 780 if (server == null) { 781 LOG.error("Server " + hostname + ":" + port + " is not up. Giving up."); 782 throw new Exception("Server " + hostname + ":" + port + " to load regions not online"); 783 } 784 return server; 785 } 786 787 private List<RegionInfo> readRegionsFromFile(String filename) throws IOException { 788 List<RegionInfo> regions = new ArrayList<>(); 789 File f = new File(filename); 790 if (!f.exists()) { 791 return regions; 792 } 793 try ( 794 DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(f)))) { 795 int numRegions = dis.readInt(); 796 int index = 0; 797 while (index < numRegions) { 798 regions.add(RegionInfo.parseFromOrNull(Bytes.readByteArray(dis))); 799 index++; 800 } 801 } catch (IOException e) { 802 LOG.error("Error while reading regions from file:" + filename, e); 803 throw e; 804 } 805 return regions; 806 } 807 808 /** 809 * Write the number of regions moved in the first line followed by regions moved in subsequent 810 * lines 811 */ 812 private void writeFile(String filename, List<RegionInfo> movedRegions) throws IOException { 813 try (DataOutputStream dos = 814 new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)))) { 815 dos.writeInt(movedRegions.size()); 816 for (RegionInfo region : movedRegions) { 817 Bytes.writeByteArray(dos, RegionInfo.toByteArray(region)); 818 } 819 } catch (IOException e) { 820 LOG.error("ERROR: Was Not able to write regions moved to output file but moved " 821 + movedRegions.size() + " regions", e); 822 throw e; 823 } 824 } 825 826 private void deleteFile(String filename) { 827 File f = new File(filename); 828 if (f.exists()) { 829 f.delete(); 830 } 831 } 832 833 /** 834 * @param filename The file should have 'host:port' per line 835 * @return List of servers from the file in format 'hostname:port'. 836 */ 837 private List<String> readServersFromFile(String filename) throws IOException { 838 List<String> servers = new ArrayList<>(); 839 if (filename != null) { 840 try { 841 Files.readAllLines(Paths.get(filename)).stream().map(String::trim) 842 .filter(((Predicate<String>) String::isEmpty).negate()).map(String::toLowerCase) 843 .forEach(servers::add); 844 } catch (IOException e) { 845 LOG.error("Exception while reading servers from file,", e); 846 throw e; 847 } 848 } 849 return servers; 850 } 851 852 /** 853 * Designates or excludes the servername whose hostname and port portion matches the list given in 854 * the file. Example:<br> 855 * If you want to designated RSs, suppose designatedFile has RS1, regionServers has RS1, RS2 and 856 * RS3. When we call includeExcludeRegionServers(designatedFile, regionServers, true), RS2 and RS3 857 * are removed from regionServers list so that regions can move to only RS1. If you want to 858 * exclude RSs, suppose excludeFile has RS1, regionServers has RS1, RS2 and RS3. When we call 859 * includeExcludeRegionServers(excludeFile, servers, false), RS1 is removed from regionServers 860 * list so that regions can move to only RS2 and RS3. 861 */ 862 private void includeExcludeRegionServers(String fileName, List<ServerName> regionServers, 863 boolean isInclude) throws IOException { 864 if (fileName != null) { 865 List<String> servers = readServersFromFile(fileName); 866 if (servers.isEmpty()) { 867 LOG.warn("No servers provided in the file: {}.", fileName); 868 return; 869 } 870 Iterator<ServerName> i = regionServers.iterator(); 871 while (i.hasNext()) { 872 String rs = i.next().getServerName(); 873 String rsPort = rs.split(ServerName.SERVERNAME_SEPARATOR)[0].toLowerCase() + ":" 874 + rs.split(ServerName.SERVERNAME_SEPARATOR)[1]; 875 if (isInclude != servers.contains(rsPort)) { 876 i.remove(); 877 } 878 } 879 } 880 } 881 882 /** 883 * Exclude master from list of RSs to move regions to 884 */ 885 private void stripMaster(List<ServerName> regionServers) throws IOException { 886 ServerName master = admin.getClusterMetrics(EnumSet.of(Option.MASTER)).getMasterName(); 887 stripServer(regionServers, master.getHostname(), master.getPort()); 888 } 889 890 /** 891 * Remove the servername whose hostname and port portion matches from the passed array of servers. 892 * Returns as side-effect the servername removed. 893 * @return server removed from list of Region Servers 894 */ 895 private ServerName stripServer(List<ServerName> regionServers, String hostname, int port) { 896 for (Iterator<ServerName> iter = regionServers.iterator(); iter.hasNext();) { 897 ServerName server = iter.next(); 898 if ( 899 server.getAddress().getHostName().equalsIgnoreCase(hostname) 900 && server.getAddress().getPort() == port 901 ) { 902 iter.remove(); 903 return server; 904 } 905 } 906 return null; 907 } 908 909 @Override 910 protected void addOptions() { 911 this.addRequiredOptWithArg("r", "regionserverhost", "region server <hostname>|<hostname:port>"); 912 this.addRequiredOptWithArg("o", "operation", 913 "Expected: load/unload/unload_from_rack/isolate_regions"); 914 this.addOptWithArg("m", "maxthreads", 915 "Define the maximum number of threads to use to unload and reload the regions"); 916 this.addOptWithArg("i", "isolateRegionIds", 917 "Comma separated list of Region IDs hash to isolate on a RegionServer and put region server" 918 + " in draining mode. This option should only be used with '-o isolate_regions'." 919 + " By putting region server in decommission/draining mode, master can't assign any" 920 + " new region on this server. If one or more regions are not found OR failed to isolate" 921 + " successfully, utility will exist without putting RS in draining/decommission mode." 922 + " Ex. --isolateRegionIds id1,id2,id3 OR -i id1,id2,id3"); 923 this.addOptWithArg("x", "excludefile", 924 "File with <hostname:port> per line to exclude as unload targets; default excludes only " 925 + "target host; useful for rack decommisioning."); 926 this.addOptWithArg("d", "designatedfile", 927 "File with <hostname:port> per line as unload targets;" + "default is all online hosts"); 928 this.addOptWithArg("f", "filename", 929 "File to save regions list into unloading, or read from loading; " 930 + "default /tmp/<usernamehostname:port>"); 931 this.addOptNoArg("n", "noack", 932 "Turn on No-Ack mode(default: false) which won't check if region is online on target " 933 + "RegionServer, hence best effort. This is more performant in unloading and loading " 934 + "but might lead to region being unavailable for some time till master reassigns it " 935 + "in case the move failed"); 936 this.addOptWithArg("t", "timeout", "timeout in seconds after which the tool will exit " 937 + "irrespective of whether it finished or not;default Integer.MAX_VALUE"); 938 } 939 940 @Override 941 protected void processOptions(CommandLine cmd) { 942 String hostname = cmd.getOptionValue("r"); 943 rmbuilder = new RegionMoverBuilder(hostname, getConf()); 944 this.loadUnload = cmd.getOptionValue("o").toLowerCase(Locale.ROOT); 945 if (cmd.hasOption('m')) { 946 rmbuilder.maxthreads(Integer.parseInt(cmd.getOptionValue('m'))); 947 } 948 if (this.loadUnload.equals("isolate_regions") && cmd.hasOption("isolateRegionIds")) { 949 rmbuilder 950 .isolateRegionIdArray(Arrays.asList(cmd.getOptionValue("isolateRegionIds").split(","))); 951 } 952 if (cmd.hasOption('n')) { 953 rmbuilder.ack(false); 954 } 955 if (cmd.hasOption('f')) { 956 rmbuilder.filename(cmd.getOptionValue('f')); 957 } 958 if (cmd.hasOption('x')) { 959 rmbuilder.excludeFile(cmd.getOptionValue('x')); 960 } 961 if (cmd.hasOption('d')) { 962 rmbuilder.designatedFile(cmd.getOptionValue('d')); 963 } 964 if (cmd.hasOption('t')) { 965 rmbuilder.timeout(Integer.parseInt(cmd.getOptionValue('t'))); 966 } 967 } 968 969 @Override 970 protected int doWork() throws Exception { 971 boolean success; 972 try (RegionMover rm = rmbuilder.build()) { 973 if (loadUnload.equalsIgnoreCase("load")) { 974 success = rm.load(); 975 } else if (loadUnload.equalsIgnoreCase("unload")) { 976 success = rm.unload(); 977 } else if (loadUnload.equalsIgnoreCase("unload_from_rack")) { 978 success = rm.unloadFromRack(); 979 } else if (loadUnload.equalsIgnoreCase("isolate_regions")) { 980 if (rm.isolateRegionIdArray != null && !rm.isolateRegionIdArray.isEmpty()) { 981 success = rm.isolateRegions(); 982 } else { 983 LOG.error("Missing -i/--isolate_regions option with '-o isolate_regions' option"); 984 LOG.error("Use -h or --help for usage instructions"); 985 printUsage(); 986 success = false; 987 } 988 } else { 989 printUsage(); 990 success = false; 991 } 992 } 993 return (success ? 0 : 1); 994 } 995 996 public static void main(String[] args) { 997 try (RegionMover mover = new RegionMover()) { 998 mover.doStaticMain(args); 999 } 1000 } 1001}