001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019
020package org.apache.hadoop.hbase.util;
021
022import java.io.BufferedReader;
023import java.io.DataInputStream;
024import java.io.DataOutputStream;
025import java.io.File;
026import java.io.FileInputStream;
027import java.io.FileOutputStream;
028import java.io.FileReader;
029import java.io.IOException;
030import java.util.ArrayList;
031import java.util.Collections;
032import java.util.EnumSet;
033import java.util.Iterator;
034import java.util.List;
035import java.util.Locale;
036import java.util.concurrent.Callable;
037import java.util.concurrent.CancellationException;
038import java.util.concurrent.ExecutionException;
039import java.util.concurrent.ExecutorService;
040import java.util.concurrent.Executors;
041import java.util.concurrent.Future;
042import java.util.concurrent.TimeUnit;
043import java.util.concurrent.TimeoutException;
044import org.apache.hadoop.conf.Configuration;
045import org.apache.hadoop.hbase.ClusterMetrics.Option;
046import org.apache.hadoop.hbase.HBaseConfiguration;
047import org.apache.hadoop.hbase.HConstants;
048import org.apache.hadoop.hbase.ServerName;
049import org.apache.hadoop.hbase.TableName;
050import org.apache.hadoop.hbase.client.Admin;
051import org.apache.hadoop.hbase.client.Connection;
052import org.apache.hadoop.hbase.client.ConnectionFactory;
053import org.apache.hadoop.hbase.client.Get;
054import org.apache.hadoop.hbase.client.RegionInfo;
055import org.apache.hadoop.hbase.client.Result;
056import org.apache.hadoop.hbase.client.ResultScanner;
057import org.apache.hadoop.hbase.client.Scan;
058import org.apache.hadoop.hbase.client.Table;
059import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
060import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
061import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
062import org.apache.yetus.audience.InterfaceAudience;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066import org.apache.hbase.thirdparty.org.apache.commons.cli.CommandLine;
067
068/**
069 * Tool for loading/unloading regions to/from given regionserver This tool can be run from Command
070 * line directly as a utility. Supports Ack/No Ack mode for loading/unloading operations.Ack mode
071 * acknowledges if regions are online after movement while noAck mode is best effort mode that
072 * improves performance but will still move on if region is stuck/not moved. Motivation behind noAck
073 * mode being RS shutdown where even if a Region is stuck, upon shutdown master will move it
074 * anyways. This can also be used by constructiong an Object using the builder and then calling
075 * {@link #load()} or {@link #unload()} methods for the desired operations.
076 */
077@InterfaceAudience.Public
078public class RegionMover extends AbstractHBaseTool {
079  public static final String MOVE_RETRIES_MAX_KEY = "hbase.move.retries.max";
080  public static final String MOVE_WAIT_MAX_KEY = "hbase.move.wait.max";
081  public static final String SERVERSTART_WAIT_MAX_KEY = "hbase.serverstart.wait.max";
082  public static final int DEFAULT_MOVE_RETRIES_MAX = 5;
083  public static final int DEFAULT_MOVE_WAIT_MAX = 60;
084  public static final int DEFAULT_SERVERSTART_WAIT_MAX = 180;
085  static final Logger LOG = LoggerFactory.getLogger(RegionMover.class);
086  private RegionMoverBuilder rmbuilder;
087  private boolean ack = true;
088  private int maxthreads = 1;
089  private int timeout;
090  private String loadUnload;
091  private String hostname;
092  private String filename;
093  private String excludeFile;
094  private int port;
095
096  private RegionMover(RegionMoverBuilder builder) {
097    this.hostname = builder.hostname;
098    this.filename = builder.filename;
099    this.excludeFile = builder.excludeFile;
100    this.maxthreads = builder.maxthreads;
101    this.ack = builder.ack;
102    this.port = builder.port;
103    this.timeout = builder.timeout;
104  }
105
106  private RegionMover() {
107  }
108
109  /**
110   * Builder for Region mover. Use the {@link #build()} method to create RegionMover object. Has
111   * {@link #filename(String)}, {@link #excludeFile(String)}, {@link #maxthreads(int)},
112   * {@link #ack(boolean)}, {@link #timeout(int)} methods to set the corresponding options
113   */
114  public static class RegionMoverBuilder {
115    private boolean ack = true;
116    private int maxthreads = 1;
117    private int timeout = Integer.MAX_VALUE;
118    private String hostname;
119    private String filename;
120    private String excludeFile = null;
121    String defaultDir = System.getProperty("java.io.tmpdir");
122
123    private int port = HConstants.DEFAULT_REGIONSERVER_PORT;
124
125    /**
126     * @param hostname Hostname to unload regions from or load regions to. Can be either hostname
127     *     or hostname:port.
128     */
129    public RegionMoverBuilder(String hostname) {
130      String[] splitHostname = hostname.toLowerCase().split(":");
131      this.hostname = splitHostname[0];
132      if (splitHostname.length == 2) {
133        this.port = Integer.parseInt(splitHostname[1]);
134      }
135      setDefaultfilename(this.hostname);
136    }
137
138    private void setDefaultfilename(String hostname) {
139      this.filename =
140          defaultDir + File.separator + System.getProperty("user.name") + this.hostname + ":"
141              + Integer.toString(this.port);
142    }
143
144    /**
145     * Path of file where regions will be written to during unloading/read from during loading
146     * @param filename
147     * @return RegionMoverBuilder object
148     */
149    public RegionMoverBuilder filename(String filename) {
150      this.filename = filename;
151      return this;
152    }
153
154    /**
155     * Set the max number of threads that will be used to move regions
156     */
157    public RegionMoverBuilder maxthreads(int threads) {
158      this.maxthreads = threads;
159      return this;
160    }
161
162    /**
163     * Path of file containing hostnames to be excluded during region movement. Exclude file should
164     * have 'host:port' per line. Port is mandatory here as we can have many RS running on a single
165     * host.
166     */
167    public RegionMoverBuilder excludeFile(String excludefile) {
168      this.excludeFile = excludefile;
169      return this;
170    }
171
172    /**
173     * Set ack/noAck mode.
174     * <p>
175     * In ack mode regions are acknowledged before and after moving and the move is retried
176     * hbase.move.retries.max times, if unsuccessful we quit with exit code 1.No Ack mode is a best
177     * effort mode,each region movement is tried once.This can be used during graceful shutdown as
178     * even if we have a stuck region,upon shutdown it'll be reassigned anyway.
179     * <p>
180     * @param ack
181     * @return RegionMoverBuilder object
182     */
183    public RegionMoverBuilder ack(boolean ack) {
184      this.ack = ack;
185      return this;
186    }
187
188    /**
189     * Set the timeout for Load/Unload operation in seconds.This is a global timeout,threadpool for
190     * movers also have a separate time which is hbase.move.wait.max * number of regions to
191     * load/unload
192     * @param timeout in seconds
193     * @return RegionMoverBuilder object
194     */
195    public RegionMoverBuilder timeout(int timeout) {
196      this.timeout = timeout;
197      return this;
198    }
199
200    /**
201     * This method builds the appropriate RegionMover object which can then be used to load/unload
202     * using load and unload methods
203     * @return RegionMover object
204     */
205    public RegionMover build() {
206      return new RegionMover(this);
207    }
208  }
209
210  /**
211   * Loads the specified {@link #hostname} with regions listed in the {@link #filename} RegionMover
212   * Object has to be created using {@link #RegionMover(RegionMoverBuilder)}
213   * @return true if loading succeeded, false otherwise
214   * @throws ExecutionException
215   * @throws InterruptedException if the loader thread was interrupted
216   * @throws TimeoutException
217   */
218  public boolean load() throws ExecutionException, InterruptedException, TimeoutException {
219    setConf();
220    ExecutorService loadPool = Executors.newFixedThreadPool(1);
221    Future<Boolean> loadTask = loadPool.submit(new Load(this));
222    loadPool.shutdown();
223    try {
224      if (!loadPool.awaitTermination((long) this.timeout, TimeUnit.SECONDS)) {
225        LOG.warn("Timed out before finishing the loading operation. Timeout:" + this.timeout
226            + "sec");
227        loadPool.shutdownNow();
228      }
229    } catch (InterruptedException e) {
230      loadPool.shutdownNow();
231      Thread.currentThread().interrupt();
232    }
233    try {
234      return loadTask.get(5, TimeUnit.SECONDS);
235    } catch (InterruptedException e) {
236      LOG.warn("Interrupted while loading Regions on " + this.hostname, e);
237      throw e;
238    } catch (ExecutionException e) {
239      LOG.error("Error while loading regions on RegionServer " + this.hostname, e);
240      throw e;
241    }
242  }
243
244  private class Load implements Callable<Boolean> {
245
246    private RegionMover rm;
247
248    public Load(RegionMover rm) {
249      this.rm = rm;
250    }
251
252    @Override
253    public Boolean call() throws IOException {
254      Connection conn = ConnectionFactory.createConnection(rm.conf);
255      try {
256        List<RegionInfo> regionsToMove = readRegionsFromFile(rm.filename);
257        if (regionsToMove.isEmpty()) {
258          LOG.info("No regions to load.Exiting");
259          return true;
260        }
261        Admin admin = conn.getAdmin();
262        try {
263          loadRegions(admin, rm.hostname, rm.port, regionsToMove, rm.ack);
264        } finally {
265          admin.close();
266        }
267      } catch (Exception e) {
268        LOG.error("Error while loading regions to " + rm.hostname, e);
269        return false;
270      } finally {
271        conn.close();
272      }
273      return true;
274    }
275  }
276
277  /**
278   * Unload regions from given {@link #hostname} using ack/noAck mode and {@link #maxthreads}.In
279   * noAck mode we do not make sure that region is successfully online on the target region
280   * server,hence it is best effort.We do not unload regions to hostnames given in
281   * {@link #excludeFile}.
282   * @return true if unloading succeeded, false otherwise
283   * @throws InterruptedException if the unloader thread was interrupted
284   * @throws ExecutionException
285   * @throws TimeoutException
286   */
287  public boolean unload() throws InterruptedException, ExecutionException, TimeoutException {
288    setConf();
289    deleteFile(this.filename);
290    ExecutorService unloadPool = Executors.newFixedThreadPool(1);
291    Future<Boolean> unloadTask = unloadPool.submit(new Unload(this));
292    unloadPool.shutdown();
293    try {
294      if (!unloadPool.awaitTermination((long) this.timeout, TimeUnit.SECONDS)) {
295        LOG.warn("Timed out before finishing the unloading operation. Timeout:" + this.timeout
296            + "sec");
297        unloadPool.shutdownNow();
298      }
299    } catch (InterruptedException e) {
300      unloadPool.shutdownNow();
301      Thread.currentThread().interrupt();
302    }
303    try {
304      return unloadTask.get(5, TimeUnit.SECONDS);
305    } catch (InterruptedException e) {
306      LOG.warn("Interrupted while unloading Regions from " + this.hostname, e);
307      throw e;
308    } catch (ExecutionException e) {
309      LOG.error("Error while unloading regions from RegionServer " + this.hostname, e);
310      throw e;
311    }
312  }
313
314  private class Unload implements Callable<Boolean> {
315
316    List<RegionInfo> movedRegions = Collections.synchronizedList(new ArrayList<RegionInfo>());
317    private RegionMover rm;
318
319    public Unload(RegionMover rm) {
320      this.rm = rm;
321    }
322
323    @Override
324    public Boolean call() throws IOException {
325      Connection conn = ConnectionFactory.createConnection(rm.conf);
326      try {
327        Admin admin = conn.getAdmin();
328        // Get Online RegionServers
329        ArrayList<String> regionServers = getServers(admin);
330        if (LOG.isDebugEnabled()) {
331          LOG.debug("Online region servers:" + regionServers.toString());
332        }
333        // Remove the host Region server from target Region Servers list
334        String server = stripServer(regionServers, hostname, port);
335        // Remove RS present in the exclude file
336        stripExcludes(regionServers, rm.excludeFile);
337        stripMaster(regionServers, admin);
338        unloadRegions(admin, server, regionServers, rm.ack, movedRegions);
339      } catch (Exception e) {
340        LOG.error("Error while unloading regions ", e);
341        return false;
342      } finally {
343        try {
344          conn.close();
345        } catch (IOException e) {
346          // ignore
347        }
348        if (movedRegions != null) {
349          writeFile(rm.filename, movedRegions);
350        }
351      }
352      return true;
353    }
354  }
355
356  /**
357   * Creates a new configuration if not already set and sets region mover specific overrides
358   */
359  private void setConf() {
360    if (conf == null) {
361      conf = HBaseConfiguration.create();
362      conf.setInt("hbase.client.prefetch.limit", 1);
363      conf.setInt("hbase.client.pause", 500);
364      conf.setInt("hbase.client.retries.number", 100);
365    }
366  }
367
368  private void loadRegions(Admin admin, String hostname, int port,
369      List<RegionInfo> regionsToMove, boolean ack) throws Exception {
370    String server = null;
371    List<RegionInfo> movedRegions = Collections.synchronizedList(new ArrayList<RegionInfo>());
372    int maxWaitInSeconds =
373        admin.getConfiguration().getInt(SERVERSTART_WAIT_MAX_KEY, DEFAULT_SERVERSTART_WAIT_MAX);
374    long maxWait = EnvironmentEdgeManager.currentTime() + maxWaitInSeconds * 1000;
375    while ((EnvironmentEdgeManager.currentTime() < maxWait) && (server == null)) {
376      try {
377        ArrayList<String> regionServers = getServers(admin);
378        // Remove the host Region server from target Region Servers list
379        server = stripServer(regionServers, hostname, port);
380        if (server != null) {
381          break;
382        }
383      } catch (IOException e) {
384        LOG.warn("Could not get list of region servers", e);
385      } catch (Exception e) {
386        LOG.info("hostname=" + hostname + " is not up yet, waiting");
387      }
388      try {
389        Thread.sleep(500);
390      } catch (InterruptedException e) {
391        LOG.error("Interrupted while waiting for " + hostname + " to be up.Quitting now", e);
392        throw e;
393      }
394    }
395    if (server == null) {
396      LOG.error("Host:" + hostname + " is not up.Giving up.");
397      throw new Exception("Host to load regions not online");
398    }
399    LOG.info("Moving " + regionsToMove.size() + " regions to " + server + " using "
400        + this.maxthreads + " threads.Ack mode:" + this.ack);
401    ExecutorService moveRegionsPool = Executors.newFixedThreadPool(this.maxthreads);
402    List<Future<Boolean>> taskList = new ArrayList<>();
403    int counter = 0;
404    while (counter < regionsToMove.size()) {
405      RegionInfo region = regionsToMove.get(counter);
406      String currentServer = getServerNameForRegion(admin, region);
407      if (currentServer == null) {
408        LOG.warn("Could not get server for Region:" + region.getEncodedName() + " moving on");
409        counter++;
410        continue;
411      } else if (server.equals(currentServer)) {
412        LOG.info("Region " + region.getRegionNameAsString() +
413            " is already on target server=" + server);
414        counter++;
415        continue;
416      }
417      if (ack) {
418        Future<Boolean> task =
419            moveRegionsPool.submit(new MoveWithAck(admin, region, currentServer, server,
420                movedRegions));
421        taskList.add(task);
422      } else {
423        Future<Boolean> task =
424            moveRegionsPool.submit(new MoveWithoutAck(admin, region, currentServer, server,
425                movedRegions));
426        taskList.add(task);
427      }
428      counter++;
429    }
430    moveRegionsPool.shutdown();
431    long timeoutInSeconds =
432        regionsToMove.size()
433            * admin.getConfiguration().getLong(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX);
434    try {
435      if (!moveRegionsPool.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS)) {
436        moveRegionsPool.shutdownNow();
437      }
438    } catch (InterruptedException e) {
439      moveRegionsPool.shutdownNow();
440      Thread.currentThread().interrupt();
441    }
442    for (Future<Boolean> future : taskList) {
443      try {
444        // if even after shutdownNow threads are stuck we wait for 5 secs max
445        if (!future.get(5, TimeUnit.SECONDS)) {
446          LOG.error("Was Not able to move region....Exiting Now");
447          throw new Exception("Could not move region Exception");
448        }
449      } catch (InterruptedException e) {
450        LOG.error("Interrupted while waiting for Thread to Complete " + e.getMessage(), e);
451        throw e;
452      } catch (ExecutionException e) {
453        LOG.error("Got Exception From Thread While moving region " + e.getMessage(), e);
454        throw e;
455      } catch (CancellationException e) {
456        LOG.error("Thread for moving region cancelled. Timeout for cancellation:"
457            + timeoutInSeconds + "secs", e);
458        throw e;
459      }
460    }
461  }
462
463  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DLS_DEAD_LOCAL_STORE",
464      justification="FB is wrong; its size is read")
465  private void unloadRegions(Admin admin, String server, ArrayList<String> regionServers,
466      boolean ack, List<RegionInfo> movedRegions) throws Exception {
467    List<RegionInfo> regionsToMove = new ArrayList<>();// FindBugs: DLS_DEAD_LOCAL_STORE
468    regionsToMove = getRegions(this.conf, server);
469    if (regionsToMove.isEmpty()) {
470      LOG.info("No Regions to move....Quitting now");
471      return;
472    } else if (regionServers.isEmpty()) {
473      LOG.warn("No Regions were moved - no servers available");
474      throw new Exception("No online region servers");
475    }
476    while (true) {
477      regionsToMove = getRegions(this.conf, server);
478      regionsToMove.removeAll(movedRegions);
479      if (regionsToMove.isEmpty()) {
480        break;
481      }
482      int counter = 0;
483      LOG.info("Moving " + regionsToMove.size() + " regions from " + this.hostname + " to "
484          + regionServers.size() + " servers using " + this.maxthreads + " threads .Ack Mode:"
485          + ack);
486      ExecutorService moveRegionsPool = Executors.newFixedThreadPool(this.maxthreads);
487      List<Future<Boolean>> taskList = new ArrayList<>();
488      int serverIndex = 0;
489      while (counter < regionsToMove.size()) {
490        if (ack) {
491          Future<Boolean> task =
492              moveRegionsPool.submit(new MoveWithAck(admin, regionsToMove.get(counter), server,
493                  regionServers.get(serverIndex), movedRegions));
494          taskList.add(task);
495        } else {
496          Future<Boolean> task =
497              moveRegionsPool.submit(new MoveWithoutAck(admin, regionsToMove.get(counter), server,
498                  regionServers.get(serverIndex), movedRegions));
499          taskList.add(task);
500        }
501        counter++;
502        serverIndex = (serverIndex + 1) % regionServers.size();
503      }
504      moveRegionsPool.shutdown();
505      long timeoutInSeconds =
506          regionsToMove.size()
507              * admin.getConfiguration().getLong(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX);
508      try {
509        if (!moveRegionsPool.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS)) {
510          moveRegionsPool.shutdownNow();
511        }
512      } catch (InterruptedException e) {
513        moveRegionsPool.shutdownNow();
514        Thread.currentThread().interrupt();
515      }
516      for (Future<Boolean> future : taskList) {
517        try {
518          // if even after shutdownNow threads are stuck we wait for 5 secs max
519          if (!future.get(5, TimeUnit.SECONDS)) {
520            LOG.error("Was Not able to move region....Exiting Now");
521            throw new Exception("Could not move region Exception");
522          }
523        } catch (InterruptedException e) {
524          LOG.error("Interrupted while waiting for Thread to Complete " + e.getMessage(), e);
525          throw e;
526        } catch (ExecutionException e) {
527          LOG.error("Got Exception From Thread While moving region " + e.getMessage(), e);
528          throw e;
529        } catch (CancellationException e) {
530          LOG.error("Thread for moving region cancelled. Timeout for cancellation:"
531              + timeoutInSeconds + "secs", e);
532          throw e;
533        }
534      }
535    }
536  }
537
538  /**
539   * Move Regions and make sure that they are up on the target server.If a region movement fails we
540   * exit as failure
541   */
542  private class MoveWithAck implements Callable<Boolean> {
543    private Admin admin;
544    private RegionInfo region;
545    private String targetServer;
546    private List<RegionInfo> movedRegions;
547    private String sourceServer;
548
549    public MoveWithAck(Admin admin, RegionInfo regionInfo, String sourceServer,
550        String targetServer, List<RegionInfo> movedRegions) {
551      this.admin = admin;
552      this.region = regionInfo;
553      this.targetServer = targetServer;
554      this.movedRegions = movedRegions;
555      this.sourceServer = sourceServer;
556    }
557
558    @Override
559    public Boolean call() throws IOException, InterruptedException {
560      boolean moved = false;
561      int count = 0;
562      int retries = admin.getConfiguration().getInt(MOVE_RETRIES_MAX_KEY, DEFAULT_MOVE_RETRIES_MAX);
563      int maxWaitInSeconds =
564          admin.getConfiguration().getInt(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX);
565      long startTime = EnvironmentEdgeManager.currentTime();
566      boolean sameServer = true;
567      // Assert we can scan the region in its current location
568      isSuccessfulScan(admin, region);
569      LOG.info("Moving region:" + region.getEncodedName() + " from " + sourceServer + " to "
570          + targetServer);
571      while (count < retries && sameServer) {
572        if (count > 0) {
573          LOG.info("Retry " + Integer.toString(count) + " of maximum " + Integer.toString(retries));
574        }
575        count = count + 1;
576        admin.move(region.getEncodedNameAsBytes(), Bytes.toBytes(targetServer));
577        long maxWait = startTime + (maxWaitInSeconds * 1000);
578        while (EnvironmentEdgeManager.currentTime() < maxWait) {
579          sameServer = isSameServer(admin, region, sourceServer);
580          if (!sameServer) {
581            break;
582          }
583          Thread.sleep(100);
584        }
585      }
586      if (sameServer) {
587        LOG.error("Region: " + region.getRegionNameAsString() + " stuck on " + this.sourceServer
588            + ",newServer=" + this.targetServer);
589      } else {
590        isSuccessfulScan(admin, region);
591        LOG.info("Moved Region "
592            + region.getRegionNameAsString()
593            + " cost:"
594            + String.format("%.3f",
595              (float) (EnvironmentEdgeManager.currentTime() - startTime) / 1000));
596        moved = true;
597        movedRegions.add(region);
598      }
599      return moved;
600    }
601  }
602
603  /**
604   * Move Regions without Acknowledging.Usefule in case of RS shutdown as we might want to shut the
605   * RS down anyways and not abort on a stuck region. Improves movement performance
606   */
607  private static class MoveWithoutAck implements Callable<Boolean> {
608    private Admin admin;
609    private RegionInfo region;
610    private String targetServer;
611    private List<RegionInfo> movedRegions;
612    private String sourceServer;
613
614    public MoveWithoutAck(Admin admin, RegionInfo regionInfo, String sourceServer,
615        String targetServer, List<RegionInfo> movedRegions) {
616      this.admin = admin;
617      this.region = regionInfo;
618      this.targetServer = targetServer;
619      this.movedRegions = movedRegions;
620      this.sourceServer = sourceServer;
621    }
622
623    @Override
624    public Boolean call() {
625      try {
626        LOG.info("Moving region:" + region.getEncodedName() + " from " + sourceServer + " to "
627            + targetServer);
628        admin.move(region.getEncodedNameAsBytes(), Bytes.toBytes(targetServer));
629        LOG.info("Moved " + region.getEncodedName() + " from " + sourceServer + " to "
630            + targetServer);
631      } catch (Exception e) {
632        LOG.error("Error Moving Region:" + region.getEncodedName(), e);
633      } finally {
634        // we add region to the moved regions list in No Ack Mode since this is best effort
635        movedRegions.add(region);
636      }
637      return true;
638    }
639  }
640
641  private List<RegionInfo> readRegionsFromFile(String filename) throws IOException {
642    List<RegionInfo> regions = new ArrayList<>();
643    File f = new File(filename);
644    if (!f.exists()) {
645      return regions;
646    }
647    FileInputStream fis = null;
648    DataInputStream dis = null;
649    try {
650      fis = new FileInputStream(f);
651      dis = new DataInputStream(fis);
652      int numRegions = dis.readInt();
653      int index = 0;
654      while (index < numRegions) {
655        regions.add(RegionInfo.parseFromOrNull(Bytes.readByteArray(dis)));
656        index++;
657      }
658    } catch (IOException e) {
659      LOG.error("Error while reading regions from file:" + filename, e);
660      throw e;
661    } finally {
662      if (dis != null) {
663        dis.close();
664      }
665      if (fis != null) {
666        fis.close();
667      }
668    }
669    return regions;
670  }
671
672  /**
673   * Get online regions of the passed server
674   * @param conf
675   * @param server
676   * @return List of Regions online on the server
677   * @throws IOException
678   */
679  private List<RegionInfo> getRegions(Configuration conf, String server) throws IOException {
680    Connection conn = ConnectionFactory.createConnection(conf);
681    try {
682      return conn.getAdmin().getRegions(ServerName.valueOf(server));
683    } finally {
684      conn.close();
685    }
686  }
687
688  /**
689   * Write the number of regions moved in the first line followed by regions moved in subsequent
690   * lines
691   * @param filename
692   * @param movedRegions
693   * @throws IOException
694   */
695  private void writeFile(String filename, List<RegionInfo> movedRegions) throws IOException {
696    FileOutputStream fos = null;
697    DataOutputStream dos = null;
698    try {
699      fos = new FileOutputStream(filename);
700      dos = new DataOutputStream(fos);
701      dos.writeInt(movedRegions.size());
702      for (RegionInfo region : movedRegions) {
703        Bytes.writeByteArray(dos, RegionInfo.toByteArray(region));
704      }
705    } catch (IOException e) {
706      LOG.error("ERROR: Was Not able to write regions moved to output file but moved "
707          + movedRegions.size() + " regions", e);
708      throw e;
709    } finally {
710      if (dos != null) {
711        dos.close();
712      }
713      if (fos != null) {
714        fos.close();
715      }
716    }
717  }
718
719  /**
720   * Excludes the servername whose hostname and port portion matches the list given in exclude file
721   * @param regionServers
722   * @param excludeFile
723   * @throws IOException
724   */
725  private void stripExcludes(ArrayList<String> regionServers, String excludeFile)
726      throws IOException {
727    if (excludeFile != null) {
728      ArrayList<String> excludes = readExcludes(excludeFile);
729      Iterator<String> i = regionServers.iterator();
730      while (i.hasNext()) {
731        String rs = i.next();
732        String rsPort =
733            rs.split(ServerName.SERVERNAME_SEPARATOR)[0] + ":"
734                + rs.split(ServerName.SERVERNAME_SEPARATOR)[1];
735        if (excludes.contains(rsPort)) {
736          i.remove();
737        }
738      }
739      LOG.info("Valid Region server targets are:" + regionServers.toString());
740      LOG.info("Excluded Servers are" + excludes.toString());
741    }
742  }
743
744  /**
745   * Exclude master from list of RSs to move regions to
746   * @param regionServers
747   * @param admin
748   * @throws IOException
749   */
750  private void stripMaster(ArrayList<String> regionServers, Admin admin) throws IOException {
751    ServerName master = admin.getClusterMetrics(EnumSet.of(Option.MASTER)).getMasterName();
752    String masterHostname = master.getHostname();
753    int masterPort = master.getPort();
754    try {
755      stripServer(regionServers, masterHostname, masterPort);
756    } catch (Exception e) {
757      LOG.warn("Could not remove master from list of RS", e);
758    }
759  }
760
761  /**
762   * @return List of servers from the exclude file in format 'hostname:port'.
763   */
764  private ArrayList<String> readExcludes(String excludeFile) throws IOException {
765    ArrayList<String> excludeServers = new ArrayList<>();
766    if (excludeFile == null) {
767      return excludeServers;
768    } else {
769      File f = new File(excludeFile);
770      String line;
771      BufferedReader br = null;
772      try {
773        br = new BufferedReader(new FileReader(f));
774        while ((line = br.readLine()) != null) {
775          line = line.trim();
776          if (!line.equals("")) {
777            excludeServers.add(line);
778          }
779        }
780      } catch (IOException e) {
781        LOG.warn("Exception while reading excludes file,continuing anyways", e);
782      } finally {
783        if (br != null) {
784          br.close();
785        }
786      }
787      return excludeServers;
788    }
789  }
790
791  /**
792   * Remove the servername whose hostname and port portion matches from the passed array of servers.
793   * Returns as side-effect the servername removed.
794   * @param regionServers
795   * @param hostname
796   * @param port
797   * @return server removed from list of Region Servers
798   * @throws Exception
799   */
800  private String stripServer(ArrayList<String> regionServers, String hostname, int port)
801      throws Exception {
802    String server = null;
803    String portString = Integer.toString(port);
804    Iterator<String> i = regionServers.iterator();
805    int noOfRs = regionServers.size();
806    while (i.hasNext()) {
807      server = i.next();
808      String[] splitServer = server.split(ServerName.SERVERNAME_SEPARATOR);
809      if (splitServer[0].equalsIgnoreCase(hostname) && splitServer[1].equals(portString)) {
810        i.remove();
811        return server;
812      }
813    }
814    if (regionServers.size() >= noOfRs) {
815      throw new Exception("Server " + hostname + ":" + Integer.toString(port)
816          + " is not in list of online servers(Offline/Incorrect)");
817    }
818    return server;
819  }
820
821  /**
822   * Get Arraylist of Servers in the cluster
823   * @param admin
824   * @return ArrayList of online region servers
825   * @throws IOException
826   */
827  private ArrayList<String> getServers(Admin admin) throws IOException {
828    ArrayList<ServerName> serverInfo = new ArrayList<>(
829        admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)).getLiveServerMetrics().keySet());
830    ArrayList<String> regionServers = new ArrayList<>(serverInfo.size());
831    for (ServerName server : serverInfo) {
832      regionServers.add(server.getServerName().toLowerCase());
833    }
834    return regionServers;
835  }
836
837  private void deleteFile(String filename) {
838    File f = new File(filename);
839    if (f.exists()) {
840      f.delete();
841    }
842  }
843
844  /**
845   * Tries to scan a row from passed region
846   * @param admin
847   * @param region
848   * @throws IOException
849   */
850  private void isSuccessfulScan(Admin admin, RegionInfo region) throws IOException {
851    Scan scan = new Scan(region.getStartKey());
852    scan.setBatch(1);
853    scan.setCaching(1);
854    scan.setFilter(new FirstKeyOnlyFilter());
855    try {
856      Table table = admin.getConnection().getTable(region.getTable());
857      try {
858        ResultScanner scanner = table.getScanner(scan);
859        try {
860          scanner.next();
861        } finally {
862          scanner.close();
863        }
864      } finally {
865        table.close();
866      }
867    } catch (IOException e) {
868      LOG.error("Could not scan region:" + region.getEncodedName(), e);
869      throw e;
870    }
871  }
872
873  /**
874   * Returns true if passed region is still on serverName when we look at hbase:meta.
875   * @param admin
876   * @param region
877   * @param serverName
878   * @return true if region is hosted on serverName otherwise false
879   * @throws IOException
880   */
881  private boolean isSameServer(Admin admin, RegionInfo region, String serverName)
882      throws IOException {
883    String serverForRegion = getServerNameForRegion(admin, region);
884    if (serverForRegion != null && serverForRegion.equals(serverName)) {
885      return true;
886    }
887    return false;
888  }
889
890  /**
891   * Get servername that is up in hbase:meta hosting the given region. this is hostname + port +
892   * startcode comma-delimited. Can return null
893   * @param admin
894   * @param region
895   * @return regionServer hosting the given region
896   * @throws IOException
897   */
898  private String getServerNameForRegion(Admin admin, RegionInfo region) throws IOException {
899    String server = null;
900    if (!admin.isTableEnabled(region.getTable())) {
901      return null;
902    }
903    if (region.isMetaRegion()) {
904      ZKWatcher zkw = new ZKWatcher(admin.getConfiguration(), "region_mover", null);
905      MetaTableLocator locator = new MetaTableLocator();
906      int maxWaitInSeconds =
907          admin.getConfiguration().getInt(MOVE_WAIT_MAX_KEY, DEFAULT_MOVE_WAIT_MAX);
908      try {
909        server = locator.waitMetaRegionLocation(zkw, maxWaitInSeconds * 1000).toString();
910      } catch (InterruptedException e) {
911        LOG.error("Interrupted while waiting for location of Meta", e);
912      } finally {
913        if (zkw != null) {
914          zkw.close();
915        }
916      }
917    } else {
918      Table table = admin.getConnection().getTable(TableName.META_TABLE_NAME);
919      try {
920        Get get = new Get(region.getRegionName());
921        get.addColumn(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER);
922        get.addColumn(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER);
923        Result result = table.get(get);
924        if (result != null) {
925          byte[] servername =
926              result.getValue(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER);
927          byte[] startcode =
928              result.getValue(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER);
929          if (servername != null) {
930            server = Bytes.toString(servername).replaceFirst(":", ",").toLowerCase() + "," +
931                Bytes.toLong(startcode);
932          }
933        }
934      } catch (IOException e) {
935        LOG.error("Could not get Server Name for region:" + region.getEncodedName(), e);
936        throw e;
937      } finally {
938        table.close();
939      }
940    }
941    return server;
942  }
943
944  @Override
945  protected void addOptions() {
946    this.addRequiredOptWithArg("r", "regionserverhost", "region server <hostname>|<hostname:port>");
947    this.addRequiredOptWithArg("o", "operation", "Expected: load/unload");
948    this.addOptWithArg("m", "maxthreads",
949      "Define the maximum number of threads to use to unload and reload the regions");
950    this.addOptWithArg("x", "excludefile",
951      "File with <hostname:port> per line to exclude as unload targets; default excludes only "
952          + "target host; useful for rack decommisioning.");
953    this.addOptWithArg("f", "filename",
954      "File to save regions list into unloading, or read from loading; "
955          + "default /tmp/<usernamehostname:port>");
956    this.addOptNoArg("n", "noack",
957      "Turn on No-Ack mode(default: false) which won't check if region is online on target "
958          + "RegionServer, hence best effort. This is more performant in unloading and loading "
959          + "but might lead to region being unavailable for some time till master reassigns it "
960          + "in case the move failed");
961    this.addOptWithArg("t", "timeout", "timeout in seconds after which the tool will exit "
962        + "irrespective of whether it finished or not;default Integer.MAX_VALUE");
963  }
964
965  @Override
966  protected void processOptions(CommandLine cmd) {
967    String hostname = cmd.getOptionValue("r");
968    rmbuilder = new RegionMoverBuilder(hostname);
969    if (cmd.hasOption('m')) {
970      rmbuilder.maxthreads(Integer.parseInt(cmd.getOptionValue('m')));
971    }
972    if (cmd.hasOption('n')) {
973      rmbuilder.ack(false);
974    }
975    if (cmd.hasOption('f')) {
976      rmbuilder.filename(cmd.getOptionValue('f'));
977    }
978    if (cmd.hasOption('x')) {
979      rmbuilder.excludeFile(cmd.getOptionValue('x'));
980    }
981    if (cmd.hasOption('t')) {
982      rmbuilder.timeout(Integer.parseInt(cmd.getOptionValue('t')));
983    }
984    this.loadUnload = cmd.getOptionValue("o").toLowerCase(Locale.ROOT);
985  }
986
987  @Override
988  protected int doWork() throws Exception {
989    boolean success;
990    RegionMover rm = rmbuilder.build();
991    if (loadUnload.equalsIgnoreCase("load")) {
992      success = rm.load();
993    } else if (loadUnload.equalsIgnoreCase("unload")) {
994      success = rm.unload();
995    } else {
996      printUsage();
997      success = false;
998    }
999    return (success ? 0 : 1);
1000  }
1001
1002  public static void main(String[] args) {
1003    new RegionMover().doStaticMain(args);
1004  }
1005}