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.tool; 019 020import static java.lang.String.format; 021 022import java.io.FileNotFoundException; 023import java.io.IOException; 024import java.io.InterruptedIOException; 025import java.net.InetSocketAddress; 026import java.nio.ByteBuffer; 027import java.util.ArrayDeque; 028import java.util.ArrayList; 029import java.util.Arrays; 030import java.util.Collection; 031import java.util.Collections; 032import java.util.Deque; 033import java.util.HashMap; 034import java.util.HashSet; 035import java.util.List; 036import java.util.Map; 037import java.util.Map.Entry; 038import java.util.Optional; 039import java.util.Set; 040import java.util.SortedMap; 041import java.util.TreeMap; 042import java.util.UUID; 043import java.util.concurrent.Callable; 044import java.util.concurrent.CompletableFuture; 045import java.util.concurrent.ExecutionException; 046import java.util.concurrent.ExecutorService; 047import java.util.concurrent.Future; 048import java.util.concurrent.LinkedBlockingQueue; 049import java.util.concurrent.ThreadPoolExecutor; 050import java.util.concurrent.TimeUnit; 051import java.util.concurrent.atomic.AtomicInteger; 052import java.util.stream.Collectors; 053import org.apache.commons.lang3.mutable.MutableInt; 054import org.apache.hadoop.conf.Configuration; 055import org.apache.hadoop.conf.Configured; 056import org.apache.hadoop.fs.FileStatus; 057import org.apache.hadoop.fs.FileSystem; 058import org.apache.hadoop.fs.Path; 059import org.apache.hadoop.hbase.Cell; 060import org.apache.hadoop.hbase.CellUtil; 061import org.apache.hadoop.hbase.ExtendedCell; 062import org.apache.hadoop.hbase.HBaseConfiguration; 063import org.apache.hadoop.hbase.HBaseInterfaceAudience; 064import org.apache.hadoop.hbase.HConstants; 065import org.apache.hadoop.hbase.HRegionLocation; 066import org.apache.hadoop.hbase.KeyValue; 067import org.apache.hadoop.hbase.TableName; 068import org.apache.hadoop.hbase.TableNotFoundException; 069import org.apache.hadoop.hbase.client.AsyncAdmin; 070import org.apache.hadoop.hbase.client.AsyncClusterConnection; 071import org.apache.hadoop.hbase.client.AsyncTableRegionLocator; 072import org.apache.hadoop.hbase.client.ClusterConnectionFactory; 073import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 074import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 075import org.apache.hadoop.hbase.client.TableDescriptor; 076import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 077import org.apache.hadoop.hbase.io.HFileLink; 078import org.apache.hadoop.hbase.io.Reference; 079import org.apache.hadoop.hbase.io.compress.Compression.Algorithm; 080import org.apache.hadoop.hbase.io.hfile.CacheConfig; 081import org.apache.hadoop.hbase.io.hfile.HFile; 082import org.apache.hadoop.hbase.io.hfile.HFileContext; 083import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder; 084import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder; 085import org.apache.hadoop.hbase.io.hfile.HFileInfo; 086import org.apache.hadoop.hbase.io.hfile.ReaderContext; 087import org.apache.hadoop.hbase.io.hfile.ReaderContextBuilder; 088import org.apache.hadoop.hbase.regionserver.BloomType; 089import org.apache.hadoop.hbase.regionserver.StoreFileInfo; 090import org.apache.hadoop.hbase.regionserver.StoreFileReader; 091import org.apache.hadoop.hbase.regionserver.StoreFileScanner; 092import org.apache.hadoop.hbase.regionserver.StoreFileWriter; 093import org.apache.hadoop.hbase.regionserver.StoreUtils; 094import org.apache.hadoop.hbase.security.UserProvider; 095import org.apache.hadoop.hbase.security.token.FsDelegationToken; 096import org.apache.hadoop.hbase.util.Bytes; 097import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 098import org.apache.hadoop.hbase.util.FSVisitor; 099import org.apache.hadoop.hbase.util.FutureUtils; 100import org.apache.hadoop.hbase.util.Pair; 101import org.apache.hadoop.util.Tool; 102import org.apache.hadoop.util.ToolRunner; 103import org.apache.yetus.audience.InterfaceAudience; 104import org.slf4j.Logger; 105import org.slf4j.LoggerFactory; 106 107import org.apache.hbase.thirdparty.com.google.common.collect.HashMultimap; 108import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 109import org.apache.hbase.thirdparty.com.google.common.collect.Maps; 110import org.apache.hbase.thirdparty.com.google.common.collect.Multimap; 111import org.apache.hbase.thirdparty.com.google.common.collect.Multimaps; 112import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; 113 114/** 115 * The implementation for {@link BulkLoadHFiles}, and also can be executed from command line as a 116 * tool. 117 */ 118@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS) 119public class BulkLoadHFilesTool extends Configured implements BulkLoadHFiles, Tool { 120 121 private static final Logger LOG = LoggerFactory.getLogger(BulkLoadHFilesTool.class); 122 123 /** 124 * Keep locality while generating HFiles for bulkload. See HBASE-12596 125 */ 126 public static final String LOCALITY_SENSITIVE_CONF_KEY = 127 "hbase.bulkload.locality.sensitive.enabled"; 128 private static final boolean DEFAULT_LOCALITY_SENSITIVE = true; 129 130 public static final String NAME = "completebulkload"; 131 /** 132 * Whether to run validation on hfiles before loading. 133 */ 134 private static final String VALIDATE_HFILES = "hbase.loadincremental.validate.hfile"; 135 /** 136 * HBASE-24221 Support bulkLoadHFile by family to avoid long time waiting of bulkLoadHFile because 137 * of compacting at server side 138 */ 139 public static final String BULK_LOAD_HFILES_BY_FAMILY = "hbase.mapreduce.bulkload.by.family"; 140 141 public static final String FAIL_IF_NEED_SPLIT_HFILE = 142 "hbase.loadincremental.fail.if.need.split.hfile"; 143 144 // We use a '.' prefix which is ignored when walking directory trees 145 // above. It is invalid family name. 146 static final String TMP_DIR = ".tmp"; 147 148 private int maxFilesPerRegionPerFamily; 149 private boolean assignSeqIds; 150 private boolean bulkLoadByFamily; 151 152 // Source delegation token 153 private FsDelegationToken fsDelegationToken; 154 private UserProvider userProvider; 155 private int nrThreads; 156 private final AtomicInteger numRetries = new AtomicInteger(0); 157 private String bulkToken; 158 159 private List<String> clusterIds = new ArrayList<>(); 160 private boolean replicate = true; 161 private boolean failIfNeedSplitHFile = false; 162 163 public BulkLoadHFilesTool(Configuration conf) { 164 // make a copy, just to be sure we're not overriding someone else's config 165 super(new Configuration(conf)); 166 initialize(); 167 } 168 169 public void initialize() { 170 Configuration conf = getConf(); 171 // disable blockcache for tool invocation, see HBASE-10500 172 conf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0); 173 userProvider = UserProvider.instantiate(conf); 174 fsDelegationToken = new FsDelegationToken(userProvider, "renewer"); 175 assignSeqIds = conf.getBoolean(ASSIGN_SEQ_IDS, true); 176 maxFilesPerRegionPerFamily = conf.getInt(MAX_FILES_PER_REGION_PER_FAMILY, 32); 177 nrThreads = 178 conf.getInt("hbase.loadincremental.threads.max", Runtime.getRuntime().availableProcessors()); 179 bulkLoadByFamily = conf.getBoolean(BULK_LOAD_HFILES_BY_FAMILY, false); 180 failIfNeedSplitHFile = conf.getBoolean(FAIL_IF_NEED_SPLIT_HFILE, false); 181 } 182 183 // Initialize a thread pool 184 private ExecutorService createExecutorService() { 185 ThreadPoolExecutor pool = new ThreadPoolExecutor(nrThreads, nrThreads, 60, TimeUnit.SECONDS, 186 new LinkedBlockingQueue<>(), 187 new ThreadFactoryBuilder().setNameFormat("BulkLoadHFilesTool-%1$d").setDaemon(true).build()); 188 pool.allowCoreThreadTimeOut(true); 189 return pool; 190 } 191 192 private boolean isCreateTable() { 193 return "yes".equalsIgnoreCase(getConf().get(CREATE_TABLE_CONF_KEY, "yes")); 194 } 195 196 private boolean isSilence() { 197 return "yes".equalsIgnoreCase(getConf().get(IGNORE_UNMATCHED_CF_CONF_KEY, "")); 198 } 199 200 private boolean isAlwaysCopyFiles() { 201 return getConf().getBoolean(ALWAYS_COPY_FILES, false); 202 } 203 204 private static boolean shouldCopyHFileMetaKey(byte[] key) { 205 // skip encoding to keep hfile meta consistent with data block info, see HBASE-15085 206 if (Bytes.equals(key, HFileDataBlockEncoder.DATA_BLOCK_ENCODING)) { 207 return false; 208 } 209 210 return !HFileInfo.isReservedFileInfoKey(key); 211 } 212 213 /** 214 * Checks whether there is any invalid family name in HFiles to be bulk loaded. 215 */ 216 private static void validateFamiliesInHFiles(TableDescriptor tableDesc, 217 Deque<LoadQueueItem> queue, boolean silence) throws IOException { 218 Set<String> familyNames = Arrays.stream(tableDesc.getColumnFamilies()) 219 .map(ColumnFamilyDescriptor::getNameAsString).collect(Collectors.toSet()); 220 List<String> unmatchedFamilies = queue.stream().map(item -> Bytes.toString(item.getFamily())) 221 .filter(fn -> !familyNames.contains(fn)).distinct().collect(Collectors.toList()); 222 if (unmatchedFamilies.size() > 0) { 223 String msg = 224 "Unmatched family names found: unmatched family names in HFiles to be bulkloaded: " 225 + unmatchedFamilies + "; valid family names of table " + tableDesc.getTableName() 226 + " are: " + familyNames; 227 LOG.error(msg); 228 if (!silence) { 229 throw new IOException(msg); 230 } 231 } 232 } 233 234 /** 235 * Populate the Queue with given HFiles 236 */ 237 private static void populateLoadQueue(Deque<LoadQueueItem> ret, Map<byte[], List<Path>> map) { 238 map.forEach((k, v) -> v.stream().map(p -> new LoadQueueItem(k, p)).forEachOrdered(ret::add)); 239 } 240 241 private interface BulkHFileVisitor<TFamily> { 242 243 TFamily bulkFamily(byte[] familyName) throws IOException; 244 245 void bulkHFile(TFamily family, FileStatus hfileStatus) throws IOException; 246 } 247 248 /** 249 * Iterate over the bulkDir hfiles. Skip reference, HFileLink, files starting with "_". Check and 250 * skip non-valid hfiles by default, or skip this validation by setting {@link #VALIDATE_HFILES} 251 * to false. 252 */ 253 private static <TFamily> void visitBulkHFiles(FileSystem fs, Path bulkDir, 254 BulkHFileVisitor<TFamily> visitor, boolean validateHFile) throws IOException { 255 FileStatus[] familyDirStatuses = fs.listStatus(bulkDir); 256 for (FileStatus familyStat : familyDirStatuses) { 257 if (!familyStat.isDirectory()) { 258 LOG.warn("Skipping non-directory " + familyStat.getPath()); 259 continue; 260 } 261 Path familyDir = familyStat.getPath(); 262 byte[] familyName = Bytes.toBytes(familyDir.getName()); 263 // Skip invalid family 264 try { 265 ColumnFamilyDescriptorBuilder.isLegalColumnFamilyName(familyName); 266 } catch (IllegalArgumentException e) { 267 LOG.warn("Skipping invalid " + familyStat.getPath()); 268 continue; 269 } 270 TFamily family = visitor.bulkFamily(familyName); 271 272 FileStatus[] hfileStatuses = fs.listStatus(familyDir); 273 for (FileStatus hfileStatus : hfileStatuses) { 274 if (!fs.isFile(hfileStatus.getPath())) { 275 LOG.warn("Skipping non-file " + hfileStatus); 276 continue; 277 } 278 279 Path hfile = hfileStatus.getPath(); 280 // Skip "_", reference, HFileLink 281 String fileName = hfile.getName(); 282 if (fileName.startsWith("_")) { 283 continue; 284 } 285 if (StoreFileInfo.isReference(fileName)) { 286 LOG.warn("Skipping reference " + fileName); 287 continue; 288 } 289 if (HFileLink.isHFileLink(fileName)) { 290 LOG.warn("Skipping HFileLink " + fileName); 291 continue; 292 } 293 294 // Validate HFile Format if needed 295 if (validateHFile) { 296 try { 297 if (!HFile.isHFileFormat(fs, hfile)) { 298 LOG.warn("the file " + hfile + " doesn't seems to be an hfile. skipping"); 299 continue; 300 } 301 } catch (FileNotFoundException e) { 302 LOG.warn("the file " + hfile + " was removed"); 303 continue; 304 } 305 } 306 307 visitor.bulkHFile(family, hfileStatus); 308 } 309 } 310 } 311 312 /** 313 * Walk the given directory for all HFiles, and return a Queue containing all such files. 314 */ 315 private static void discoverLoadQueue(Configuration conf, Deque<LoadQueueItem> ret, Path hfofDir, 316 boolean validateHFile) throws IOException { 317 visitBulkHFiles(hfofDir.getFileSystem(conf), hfofDir, new BulkHFileVisitor<byte[]>() { 318 @Override 319 public byte[] bulkFamily(final byte[] familyName) { 320 return familyName; 321 } 322 323 @Override 324 public void bulkHFile(final byte[] family, final FileStatus hfile) { 325 long length = hfile.getLen(); 326 if ( 327 length > conf.getLong(HConstants.HREGION_MAX_FILESIZE, HConstants.DEFAULT_MAX_FILE_SIZE) 328 ) { 329 LOG.warn("Trying to bulk load hfile " + hfile.getPath() + " with size: " + length 330 + " bytes can be problematic as it may lead to oversplitting."); 331 } 332 ret.add(new LoadQueueItem(family, hfile.getPath())); 333 } 334 }, validateHFile); 335 } 336 337 /** 338 * Prepare a collection of {@code LoadQueueItem} from list of source hfiles contained in the 339 * passed directory and validates whether the prepared queue has all the valid table column 340 * families in it. 341 * @param map map of family to List of hfiles 342 * @param tableName table to which hfiles should be loaded 343 * @param queue queue which needs to be loaded into the table 344 * @param silence true to ignore unmatched column families 345 * @throws IOException If any I/O or network error occurred 346 */ 347 public static void prepareHFileQueue(AsyncClusterConnection conn, TableName tableName, 348 Map<byte[], List<Path>> map, Deque<LoadQueueItem> queue, boolean silence) throws IOException { 349 populateLoadQueue(queue, map); 350 validateFamiliesInHFiles(FutureUtils.get(conn.getAdmin().getDescriptor(tableName)), queue, 351 silence); 352 } 353 354 /** 355 * Prepare a collection of {@code LoadQueueItem} from list of source hfiles contained in the 356 * passed directory and validates whether the prepared queue has all the valid table column 357 * families in it. 358 * @param hfilesDir directory containing list of hfiles to be loaded into the table 359 * @param queue queue which needs to be loaded into the table 360 * @param validateHFile if true hfiles will be validated for its format 361 * @param silence true to ignore unmatched column families 362 * @throws IOException If any I/O or network error occurred 363 */ 364 public static void prepareHFileQueue(Configuration conf, AsyncClusterConnection conn, 365 TableName tableName, Path hfilesDir, Deque<LoadQueueItem> queue, boolean validateHFile, 366 boolean silence) throws IOException { 367 discoverLoadQueue(conf, queue, hfilesDir, validateHFile); 368 validateFamiliesInHFiles(FutureUtils.get(conn.getAdmin().getDescriptor(tableName)), queue, 369 silence); 370 } 371 372 /** 373 * Used by the replication sink to load the hfiles from the source cluster. It does the following, 374 * <ol> 375 * <li>{@link #groupOrSplitPhase(AsyncClusterConnection, TableName, ExecutorService, Deque, List)} 376 * </li> 377 * <li>{@link #bulkLoadPhase(AsyncClusterConnection, TableName, Deque, Multimap, boolean, Map)} 378 * </li> 379 * </ol> 380 * @param conn Connection to use 381 * @param tableName Table to which these hfiles should be loaded to 382 * @param queue {@code LoadQueueItem} has hfiles yet to be loaded 383 */ 384 public void loadHFileQueue(AsyncClusterConnection conn, TableName tableName, 385 Deque<LoadQueueItem> queue, boolean copyFiles) throws IOException { 386 ExecutorService pool = createExecutorService(); 387 try { 388 Multimap<ByteBuffer, LoadQueueItem> regionGroups = groupOrSplitPhase(conn, tableName, pool, 389 queue, FutureUtils.get(conn.getRegionLocator(tableName).getStartEndKeys())).getFirst(); 390 bulkLoadPhase(conn, tableName, queue, regionGroups, copyFiles, null); 391 } finally { 392 pool.shutdown(); 393 } 394 } 395 396 /** 397 * Attempts to do an atomic load of many hfiles into a region. If it fails, it returns a list of 398 * hfiles that need to be retried. If it is successful it will return an empty list. NOTE: To 399 * maintain row atomicity guarantees, region server side should succeed atomically and fails 400 * atomically. 401 * @param conn Connection to use 402 * @param tableName Table to which these hfiles should be loaded to 403 * @param copyFiles whether replicate to peer cluster while bulkloading 404 * @param first the start key of region 405 * @param lqis hfiles should be loaded 406 * @return empty list if success, list of items to retry on recoverable failure 407 */ 408 @InterfaceAudience.Private 409 protected CompletableFuture<Collection<LoadQueueItem>> tryAtomicRegionLoad( 410 final AsyncClusterConnection conn, final TableName tableName, boolean copyFiles, 411 final byte[] first, Collection<LoadQueueItem> lqis) { 412 List<Pair<byte[], String>> familyPaths = 413 lqis.stream().map(lqi -> Pair.newPair(lqi.getFamily(), lqi.getFilePath().toString())) 414 .collect(Collectors.toList()); 415 CompletableFuture<Collection<LoadQueueItem>> future = new CompletableFuture<>(); 416 FutureUtils.addListener(conn.bulkLoad(tableName, familyPaths, first, assignSeqIds, 417 fsDelegationToken.getUserToken(), bulkToken, copyFiles, clusterIds, replicate), 418 (loaded, error) -> { 419 if (error != null) { 420 LOG.error("Encountered unrecoverable error from region server", error); 421 if ( 422 getConf().getBoolean(RETRY_ON_IO_EXCEPTION, false) 423 && numRetries.get() < getConf().getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 424 HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER) 425 ) { 426 LOG.warn("Will attempt to retry loading failed HFiles. Retry #" 427 + numRetries.incrementAndGet()); 428 // return lqi's to retry 429 future.complete(lqis); 430 } else { 431 LOG.error(RETRY_ON_IO_EXCEPTION 432 + " is disabled or we have reached retry limit. Unable to recover"); 433 future.completeExceptionally(error); 434 } 435 } else { 436 if (loaded) { 437 future.complete(Collections.emptyList()); 438 } else { 439 LOG.warn("Attempt to bulk load region containing " + Bytes.toStringBinary(first) 440 + " into table " + tableName + " with files " + lqis 441 + " failed. This is recoverable and they will be retried."); 442 // return lqi's to retry 443 future.complete(lqis); 444 } 445 } 446 }); 447 return future; 448 } 449 450 /** 451 * This takes the LQI's grouped by likely regions and attempts to bulk load them. Any failures are 452 * re-queued for another pass with the groupOrSplitPhase. 453 * <p/> 454 * protected for testing. 455 */ 456 @InterfaceAudience.Private 457 protected void bulkLoadPhase(AsyncClusterConnection conn, TableName tableName, 458 Deque<LoadQueueItem> queue, Multimap<ByteBuffer, LoadQueueItem> regionGroups, boolean copyFiles, 459 Map<LoadQueueItem, ByteBuffer> item2RegionMap) throws IOException { 460 // atomically bulk load the groups. 461 List<Future<Collection<LoadQueueItem>>> loadingFutures = new ArrayList<>(); 462 for (Entry<ByteBuffer, ? extends Collection<LoadQueueItem>> entry : regionGroups.asMap() 463 .entrySet()) { 464 byte[] first = entry.getKey().array(); 465 final Collection<LoadQueueItem> lqis = entry.getValue(); 466 if (bulkLoadByFamily) { 467 groupByFamilies(lqis).values().forEach(familyQueue -> loadingFutures 468 .add(tryAtomicRegionLoad(conn, tableName, copyFiles, first, familyQueue))); 469 } else { 470 loadingFutures.add(tryAtomicRegionLoad(conn, tableName, copyFiles, first, lqis)); 471 } 472 if (item2RegionMap != null) { 473 for (LoadQueueItem lqi : lqis) { 474 item2RegionMap.put(lqi, entry.getKey()); 475 } 476 } 477 } 478 479 // get all the results. 480 for (Future<Collection<LoadQueueItem>> future : loadingFutures) { 481 try { 482 Collection<LoadQueueItem> toRetry = future.get(); 483 484 if (item2RegionMap != null) { 485 for (LoadQueueItem lqi : toRetry) { 486 item2RegionMap.remove(lqi); 487 } 488 } 489 // LQIs that are requeued to be regrouped. 490 queue.addAll(toRetry); 491 } catch (ExecutionException e1) { 492 Throwable t = e1.getCause(); 493 if (t instanceof IOException) { 494 // At this point something unrecoverable has happened. 495 // TODO Implement bulk load recovery 496 throw new IOException("BulkLoad encountered an unrecoverable problem", t); 497 } 498 LOG.error("Unexpected execution exception during bulk load", e1); 499 throw new IllegalStateException(t); 500 } catch (InterruptedException e1) { 501 LOG.error("Unexpected interrupted exception during bulk load", e1); 502 throw (InterruptedIOException) new InterruptedIOException().initCause(e1); 503 } 504 } 505 } 506 507 private Map<byte[], Collection<LoadQueueItem>> 508 groupByFamilies(Collection<LoadQueueItem> itemsInRegion) { 509 Map<byte[], Collection<LoadQueueItem>> families2Queue = new TreeMap<>(Bytes.BYTES_COMPARATOR); 510 itemsInRegion.forEach(item -> families2Queue 511 .computeIfAbsent(item.getFamily(), queue -> new ArrayList<>()).add(item)); 512 return families2Queue; 513 } 514 515 private boolean 516 checkHFilesCountPerRegionPerFamily(final Multimap<ByteBuffer, LoadQueueItem> regionGroups) { 517 for (Map.Entry<ByteBuffer, Collection<LoadQueueItem>> e : regionGroups.asMap().entrySet()) { 518 Map<byte[], MutableInt> filesMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); 519 for (LoadQueueItem lqi : e.getValue()) { 520 MutableInt count = filesMap.computeIfAbsent(lqi.getFamily(), k -> new MutableInt()); 521 count.increment(); 522 if (count.intValue() > maxFilesPerRegionPerFamily) { 523 LOG.error("Trying to load more than " + maxFilesPerRegionPerFamily + " hfiles to family " 524 + Bytes.toStringBinary(lqi.getFamily()) + " of region with start key " 525 + Bytes.toStringBinary(e.getKey())); 526 return false; 527 } 528 } 529 } 530 return true; 531 } 532 533 /** 534 * @param conn the HBase cluster connection 535 * @param tableName the table name of the table to load into 536 * @param pool the ExecutorService 537 * @param queue the queue for LoadQueueItem 538 * @param startEndKeys start and end keys 539 * @return A map that groups LQI by likely bulk load region targets and Set of missing hfiles. 540 */ 541 private Pair<Multimap<ByteBuffer, LoadQueueItem>, Set<String>> groupOrSplitPhase( 542 AsyncClusterConnection conn, TableName tableName, ExecutorService pool, 543 Deque<LoadQueueItem> queue, List<Pair<byte[], byte[]>> startEndKeys) throws IOException { 544 // <region start key, LQI> need synchronized only within this scope of this 545 // phase because of the puts that happen in futures. 546 Multimap<ByteBuffer, LoadQueueItem> rgs = HashMultimap.create(); 547 final Multimap<ByteBuffer, LoadQueueItem> regionGroups = Multimaps.synchronizedMultimap(rgs); 548 Set<String> missingHFiles = new HashSet<>(); 549 Pair<Multimap<ByteBuffer, LoadQueueItem>, Set<String>> pair = 550 new Pair<>(regionGroups, missingHFiles); 551 552 // drain LQIs and figure out bulk load groups 553 Set<Future<Pair<List<LoadQueueItem>, String>>> splittingFutures = new HashSet<>(); 554 while (!queue.isEmpty()) { 555 final LoadQueueItem item = queue.remove(); 556 final Callable<Pair<List<LoadQueueItem>, String>> call = 557 () -> groupOrSplit(conn, tableName, regionGroups, item, startEndKeys); 558 splittingFutures.add(pool.submit(call)); 559 } 560 // get all the results. All grouping and splitting must finish before 561 // we can attempt the atomic loads. 562 for (Future<Pair<List<LoadQueueItem>, String>> lqis : splittingFutures) { 563 try { 564 Pair<List<LoadQueueItem>, String> splits = lqis.get(); 565 if (splits != null) { 566 if (splits.getFirst() != null) { 567 queue.addAll(splits.getFirst()); 568 } else { 569 missingHFiles.add(splits.getSecond()); 570 } 571 } 572 } catch (ExecutionException e1) { 573 Throwable t = e1.getCause(); 574 if (t instanceof IOException) { 575 LOG.error("IOException during splitting", e1); 576 throw (IOException) t; // would have been thrown if not parallelized, 577 } 578 LOG.error("Unexpected execution exception during splitting", e1); 579 throw new IllegalStateException(t); 580 } catch (InterruptedException e1) { 581 LOG.error("Unexpected interrupted exception during splitting", e1); 582 throw (InterruptedIOException) new InterruptedIOException().initCause(e1); 583 } 584 } 585 return pair; 586 } 587 588 // unique file name for the table 589 private String getUniqueName() { 590 return UUID.randomUUID().toString().replaceAll("-", ""); 591 } 592 593 private List<LoadQueueItem> splitStoreFile(AsyncTableRegionLocator loc, LoadQueueItem item, 594 TableDescriptor tableDesc, byte[] splitKey) throws IOException { 595 Path hfilePath = item.getFilePath(); 596 byte[] family = item.getFamily(); 597 Path tmpDir = hfilePath.getParent(); 598 if (!tmpDir.getName().equals(TMP_DIR)) { 599 tmpDir = new Path(tmpDir, TMP_DIR); 600 } 601 602 LOG.info("HFile at " + hfilePath + " no longer fits inside a single " + "region. Splitting..."); 603 604 String uniqueName = getUniqueName(); 605 ColumnFamilyDescriptor familyDesc = tableDesc.getColumnFamily(family); 606 607 Path botOut = new Path(tmpDir, uniqueName + ".bottom"); 608 Path topOut = new Path(tmpDir, uniqueName + ".top"); 609 610 splitStoreFile(loc, getConf(), hfilePath, familyDesc, splitKey, botOut, topOut); 611 612 FileSystem fs = tmpDir.getFileSystem(getConf()); 613 614 // Add these back at the *front* of the queue, so there's a lower 615 // chance that the region will just split again before we get there. 616 List<LoadQueueItem> lqis = new ArrayList<>(2); 617 lqis.add(new LoadQueueItem(family, botOut)); 618 lqis.add(new LoadQueueItem(family, topOut)); 619 620 // If the current item is already the result of previous splits, 621 // we don't need it anymore. Clean up to save space. 622 // It is not part of the original input files. 623 try { 624 // Preserve original input files so a new bulk load invocation can retry if loading the split 625 // outputs fails. Only delete an input which was itself produced by an earlier split. 626 if (hfilePath.getParent().getName().equals(TMP_DIR)) { 627 fs.delete(hfilePath, false); 628 } 629 } catch (IOException e) { 630 LOG.warn("Unable to delete temporary split file " + hfilePath); 631 } 632 LOG.info("Successfully split into new HFiles " + botOut + " and " + topOut); 633 return lqis; 634 } 635 636 /** 637 * @param startEndKeys the start/end keys of regions belong to this table, the list in ascending 638 * order by start key 639 * @param key the key need to find which region belong to 640 * @return region index 641 */ 642 private int getRegionIndex(List<Pair<byte[], byte[]>> startEndKeys, byte[] key) { 643 int idx = Collections.binarySearch(startEndKeys, Pair.newPair(key, HConstants.EMPTY_END_ROW), 644 (p1, p2) -> Bytes.compareTo(p1.getFirst(), p2.getFirst())); 645 if (idx < 0) { 646 // not on boundary, returns -(insertion index). Calculate region it 647 // would be in. 648 idx = -(idx + 1) - 1; 649 } 650 return idx; 651 } 652 653 /** 654 * we can consider there is a region hole or overlap in following conditions. 1) if idx < 0,then 655 * first region info is lost. 2) if the endkey of a region is not equal to the startkey of the 656 * next region. 3) if the endkey of the last region is not empty. 657 */ 658 private void checkRegionIndexValid(int idx, List<Pair<byte[], byte[]>> startEndKeys, 659 TableName tableName) throws IOException { 660 if (idx < 0) { 661 throw new IOException("The first region info for table " + tableName + " can't be found in " 662 + TableName.META_TABLE_NAME + ". Please use hbck tool to fix it" + " first."); 663 } else if ( 664 (idx == startEndKeys.size() - 1) 665 && !Bytes.equals(startEndKeys.get(idx).getSecond(), HConstants.EMPTY_BYTE_ARRAY) 666 ) { 667 throw new IOException("The last region info for table " + tableName + " can't be found in " 668 + TableName.META_TABLE_NAME + ". Please use hbck tool to fix it" + " first."); 669 } else if ( 670 idx + 1 < startEndKeys.size() && !(Bytes.compareTo(startEndKeys.get(idx).getSecond(), 671 startEndKeys.get(idx + 1).getFirst()) == 0) 672 ) { 673 throw new IOException("The endkey of one region for table " + tableName 674 + " is not equal to the startkey of the next region in " + TableName.META_TABLE_NAME + "." 675 + " Please use hbck tool to fix it first."); 676 } 677 } 678 679 /** 680 * Attempt to assign the given load queue item into its target region group. If the hfile boundary 681 * no longer fits into a region, physically splits the hfile such that the new bottom half will 682 * fit and returns the list of LQI's corresponding to the resultant hfiles. 683 * <p/> 684 * protected for testing 685 * @throws IOException if an IO failure is encountered 686 */ 687 @InterfaceAudience.Private 688 protected Pair<List<LoadQueueItem>, String> groupOrSplit(AsyncClusterConnection conn, 689 TableName tableName, Multimap<ByteBuffer, LoadQueueItem> regionGroups, LoadQueueItem item, 690 List<Pair<byte[], byte[]>> startEndKeys) throws IOException { 691 Path hfilePath = item.getFilePath(); 692 Optional<byte[]> first, last; 693 try (HFile.Reader hfr = HFile.createReader(hfilePath.getFileSystem(getConf()), hfilePath, 694 CacheConfig.DISABLED, true, getConf())) { 695 first = hfr.getFirstRowKey(); 696 last = hfr.getLastRowKey(); 697 } catch (FileNotFoundException fnfe) { 698 LOG.debug("encountered", fnfe); 699 return new Pair<>(null, hfilePath.getName()); 700 } 701 702 LOG.info("Trying to load hfile=" + hfilePath + " first=" + first.map(Bytes::toStringBinary) 703 + " last=" + last.map(Bytes::toStringBinary)); 704 if (!first.isPresent() || !last.isPresent()) { 705 assert !first.isPresent() && !last.isPresent(); 706 // TODO what if this is due to a bad HFile? 707 LOG.info("hfile " + hfilePath + " has no entries, skipping"); 708 return null; 709 } 710 if (Bytes.compareTo(first.get(), last.get()) > 0) { 711 throw new IllegalArgumentException("Invalid range: " + Bytes.toStringBinary(first.get()) 712 + " > " + Bytes.toStringBinary(last.get())); 713 } 714 int firstKeyRegionIdx = getRegionIndex(startEndKeys, first.get()); 715 checkRegionIndexValid(firstKeyRegionIdx, startEndKeys, tableName); 716 boolean lastKeyInRange = 717 Bytes.compareTo(last.get(), startEndKeys.get(firstKeyRegionIdx).getSecond()) < 0 || Bytes 718 .equals(startEndKeys.get(firstKeyRegionIdx).getSecond(), HConstants.EMPTY_BYTE_ARRAY); 719 if (!lastKeyInRange) { 720 if (failIfNeedSplitHFile) { 721 throw new IOException( 722 "The key range of hfile=" + hfilePath + " fits into no region. " + "And because " 723 + FAIL_IF_NEED_SPLIT_HFILE + " was set to true, we just skip the next steps."); 724 } 725 int lastKeyRegionIdx = getRegionIndex(startEndKeys, last.get()); 726 int splitIdx = (firstKeyRegionIdx + lastKeyRegionIdx) / 2; 727 // make sure the splitPoint is valid in case region overlap occur, maybe the splitPoint bigger 728 // than hfile.endkey w/o this check 729 if (splitIdx != firstKeyRegionIdx) { 730 checkRegionIndexValid(splitIdx, startEndKeys, tableName); 731 } 732 byte[] splitPoint = startEndKeys.get(splitIdx).getSecond(); 733 List<LoadQueueItem> lqis = splitStoreFile(conn.getRegionLocator(tableName), item, 734 FutureUtils.get(conn.getAdmin().getDescriptor(tableName)), splitPoint); 735 736 return new Pair<>(lqis, null); 737 } 738 739 // group regions. 740 regionGroups.put(ByteBuffer.wrap(startEndKeys.get(firstKeyRegionIdx).getFirst()), item); 741 return null; 742 } 743 744 /** 745 * Split a storefile into a top and bottom half with favored nodes, maintaining the metadata, 746 * recreating bloom filters, etc. 747 */ 748 @InterfaceAudience.Private 749 static void splitStoreFile(AsyncTableRegionLocator loc, Configuration conf, Path inFile, 750 ColumnFamilyDescriptor familyDesc, byte[] splitKey, Path bottomOut, Path topOut) 751 throws IOException { 752 // Open reader with no block cache, and not in-memory 753 Reference topReference = Reference.createTopReference(splitKey); 754 Reference bottomReference = Reference.createBottomReference(splitKey); 755 756 copyHFileHalf(conf, inFile, topOut, topReference, familyDesc, loc); 757 copyHFileHalf(conf, inFile, bottomOut, bottomReference, familyDesc, loc); 758 } 759 760 private static StoreFileWriter initStoreFileWriter(Configuration conf, Cell cell, 761 HFileContext hFileContext, CacheConfig cacheConf, BloomType bloomFilterType, FileSystem fs, 762 Path outFile, AsyncTableRegionLocator loc) throws IOException { 763 if (conf.getBoolean(LOCALITY_SENSITIVE_CONF_KEY, DEFAULT_LOCALITY_SENSITIVE)) { 764 byte[] rowKey = CellUtil.cloneRow(cell); 765 HRegionLocation hRegionLocation = FutureUtils.get(loc.getRegionLocation(rowKey)); 766 InetSocketAddress[] favoredNodes = null; 767 if (null == hRegionLocation) { 768 LOG.warn("Failed get region location for rowkey {} , Using writer without favoured nodes.", 769 Bytes.toString(rowKey)); 770 return new StoreFileWriter.Builder(conf, cacheConf, fs).withFilePath(outFile) 771 .withBloomType(bloomFilterType).withFileContext(hFileContext).build(); 772 } else { 773 LOG.debug("First rowkey: [{}]", Bytes.toString(rowKey)); 774 InetSocketAddress initialIsa = 775 new InetSocketAddress(hRegionLocation.getHostname(), hRegionLocation.getPort()); 776 if (initialIsa.isUnresolved()) { 777 LOG.warn("Failed get location for region {} , Using writer without favoured nodes.", 778 hRegionLocation); 779 return new StoreFileWriter.Builder(conf, cacheConf, fs).withFilePath(outFile) 780 .withBloomType(bloomFilterType).withFileContext(hFileContext).build(); 781 } else { 782 LOG.debug("Use favored nodes writer: {}", initialIsa.getHostString()); 783 favoredNodes = new InetSocketAddress[] { initialIsa }; 784 return new StoreFileWriter.Builder(conf, cacheConf, fs).withFilePath(outFile) 785 .withBloomType(bloomFilterType).withFileContext(hFileContext) 786 .withFavoredNodes(favoredNodes).build(); 787 } 788 } 789 } else { 790 return new StoreFileWriter.Builder(conf, cacheConf, fs).withFilePath(outFile) 791 .withBloomType(bloomFilterType).withFileContext(hFileContext).build(); 792 } 793 } 794 795 /** 796 * Copy half of an HFile into a new HFile with favored nodes. 797 */ 798 private static void copyHFileHalf(Configuration conf, Path inFile, Path outFile, 799 Reference reference, ColumnFamilyDescriptor familyDescriptor, AsyncTableRegionLocator loc) 800 throws IOException { 801 FileSystem fs = inFile.getFileSystem(conf); 802 CacheConfig cacheConf = CacheConfig.DISABLED; 803 StoreFileReader halfReader = null; 804 StoreFileWriter halfWriter = null; 805 try { 806 ReaderContext context = new ReaderContextBuilder().withFileSystemAndPath(fs, inFile).build(); 807 StoreFileInfo storeFileInfo = 808 new StoreFileInfo(conf, fs, fs.getFileStatus(inFile), reference); 809 storeFileInfo.initHFileInfo(context); 810 halfReader = storeFileInfo.createReader(context, cacheConf); 811 storeFileInfo.getHFileInfo().initMetaAndIndex(halfReader.getHFileReader()); 812 Map<byte[], byte[]> fileInfo = halfReader.loadFileInfo(); 813 814 int blocksize = familyDescriptor.getBlocksize(); 815 Algorithm compression = familyDescriptor.getCompressionType(); 816 BloomType bloomFilterType = familyDescriptor.getBloomFilterType(); 817 HFileContext hFileContext = new HFileContextBuilder().withCompression(compression) 818 .withChecksumType(StoreUtils.getChecksumType(conf)) 819 .withBytesPerCheckSum(StoreUtils.getBytesPerChecksum(conf)).withBlockSize(blocksize) 820 .withDataBlockEncoding(familyDescriptor.getDataBlockEncoding()).withIncludesTags(true) 821 .withCreateTime(EnvironmentEdgeManager.currentTime()).build(); 822 823 try (StoreFileScanner scanner = 824 halfReader.getStoreFileScanner(false, false, false, Long.MAX_VALUE, 0, false)) { 825 scanner.seek(KeyValue.LOWESTKEY); 826 for (;;) { 827 ExtendedCell cell = scanner.next(); 828 if (cell == null) { 829 break; 830 } 831 if (halfWriter == null) { 832 // init halfwriter 833 halfWriter = initStoreFileWriter(conf, cell, hFileContext, cacheConf, bloomFilterType, 834 fs, outFile, loc); 835 } 836 halfWriter.append(cell); 837 } 838 } 839 for (Map.Entry<byte[], byte[]> entry : fileInfo.entrySet()) { 840 if (shouldCopyHFileMetaKey(entry.getKey())) { 841 halfWriter.appendFileInfo(entry.getKey(), entry.getValue()); 842 } 843 } 844 } finally { 845 if (halfReader != null) { 846 try { 847 halfReader.close(cacheConf.shouldEvictOnClose()); 848 } catch (IOException e) { 849 LOG.warn("failed to close hfile reader for " + inFile, e); 850 } 851 } 852 if (halfWriter != null) { 853 halfWriter.close(); 854 } 855 } 856 } 857 858 /** 859 * Infers region boundaries for a new table. 860 * <p/> 861 * Parameter: <br/> 862 * bdryMap is a map between keys to an integer belonging to {+1, -1} 863 * <ul> 864 * <li>If a key is a start key of a file, then it maps to +1</li> 865 * <li>If a key is an end key of a file, then it maps to -1</li> 866 * </ul> 867 * <p> 868 * Algo:<br/> 869 * <ol> 870 * <li>Poll on the keys in order: 871 * <ol type="a"> 872 * <li>Keep adding the mapped values to these keys (runningSum)</li> 873 * <li>Each time runningSum reaches 0, add the start Key from when the runningSum had started to a 874 * boundary list.</li> 875 * </ol> 876 * </li> 877 * <li>Return the boundary list.</li> 878 * </ol> 879 */ 880 public static byte[][] inferBoundaries(SortedMap<byte[], Integer> bdryMap) { 881 List<byte[]> keysArray = new ArrayList<>(); 882 int runningValue = 0; 883 byte[] currStartKey = null; 884 boolean firstBoundary = true; 885 886 for (Map.Entry<byte[], Integer> item : bdryMap.entrySet()) { 887 if (runningValue == 0) { 888 currStartKey = item.getKey(); 889 } 890 runningValue += item.getValue(); 891 if (runningValue == 0) { 892 if (!firstBoundary) { 893 keysArray.add(currStartKey); 894 } 895 firstBoundary = false; 896 } 897 } 898 899 return keysArray.toArray(new byte[0][]); 900 } 901 902 /** 903 * If the table is created for the first time, then "completebulkload" reads the files twice. More 904 * modifications necessary if we want to avoid doing it. 905 */ 906 private void createTable(TableName tableName, Path hfofDir, AsyncAdmin admin) throws IOException { 907 final FileSystem fs = hfofDir.getFileSystem(getConf()); 908 909 // Add column families 910 // Build a set of keys 911 List<ColumnFamilyDescriptorBuilder> familyBuilders = new ArrayList<>(); 912 SortedMap<byte[], Integer> map = new TreeMap<>(Bytes.BYTES_COMPARATOR); 913 visitBulkHFiles(fs, hfofDir, new BulkHFileVisitor<ColumnFamilyDescriptorBuilder>() { 914 @Override 915 public ColumnFamilyDescriptorBuilder bulkFamily(byte[] familyName) { 916 ColumnFamilyDescriptorBuilder builder = 917 ColumnFamilyDescriptorBuilder.newBuilder(familyName); 918 familyBuilders.add(builder); 919 return builder; 920 } 921 922 @Override 923 public void bulkHFile(ColumnFamilyDescriptorBuilder builder, FileStatus hfileStatus) 924 throws IOException { 925 Path hfile = hfileStatus.getPath(); 926 try (HFile.Reader reader = 927 HFile.createReader(fs, hfile, CacheConfig.DISABLED, true, getConf())) { 928 if (builder.getCompressionType() != reader.getFileContext().getCompression()) { 929 builder.setCompressionType(reader.getFileContext().getCompression()); 930 LOG.info("Setting compression " + reader.getFileContext().getCompression().name() 931 + " for family " + builder.getNameAsString()); 932 } 933 byte[] first = reader.getFirstRowKey().get(); 934 byte[] last = reader.getLastRowKey().get(); 935 936 LOG.info("Trying to figure out region boundaries hfile=" + hfile + " first=" 937 + Bytes.toStringBinary(first) + " last=" + Bytes.toStringBinary(last)); 938 939 // To eventually infer start key-end key boundaries 940 Integer value = map.getOrDefault(first, 0); 941 map.put(first, value + 1); 942 943 value = map.containsKey(last) ? map.get(last) : 0; 944 map.put(last, value - 1); 945 } 946 } 947 }, true); 948 949 byte[][] keys = inferBoundaries(map); 950 TableDescriptorBuilder tdBuilder = TableDescriptorBuilder.newBuilder(tableName); 951 familyBuilders.stream().map(ColumnFamilyDescriptorBuilder::build) 952 .forEachOrdered(tdBuilder::setColumnFamily); 953 FutureUtils.get(admin.createTable(tdBuilder.build(), keys)); 954 955 LOG.info("Table " + tableName + " is available!!"); 956 } 957 958 private Map<LoadQueueItem, ByteBuffer> performBulkLoad(AsyncClusterConnection conn, 959 TableName tableName, Deque<LoadQueueItem> queue, ExecutorService pool, boolean copyFile) 960 throws IOException { 961 int count = 0; 962 963 Path path = queue.peek().getFilePath(); 964 FileSystem fs = path.getFileSystem(getConf()).resolvePath(path).getFileSystem(getConf()); 965 fsDelegationToken.acquireDelegationToken(fs); 966 bulkToken = FutureUtils.get(conn.prepareBulkLoad(tableName)); 967 Pair<Multimap<ByteBuffer, LoadQueueItem>, Set<String>> pair = null; 968 969 Map<LoadQueueItem, ByteBuffer> item2RegionMap = new HashMap<>(); 970 // Assumes that region splits can happen while this occurs. 971 while (!queue.isEmpty()) { 972 // need to reload split keys each iteration. 973 final List<Pair<byte[], byte[]>> startEndKeys = 974 FutureUtils.get(conn.getRegionLocator(tableName).getStartEndKeys()); 975 if (count != 0) { 976 LOG.info("Split occurred while grouping HFiles, retry attempt " + count + " with " 977 + queue.size() + " files remaining to group or split"); 978 } 979 980 int maxRetries = getConf().getInt(HConstants.BULKLOAD_MAX_RETRIES_NUMBER, 10); 981 maxRetries = Math.max(maxRetries, startEndKeys.size() + 1); 982 if (maxRetries != 0 && count >= maxRetries) { 983 throw new IOException( 984 "Retry attempted " + count + " times without completing, bailing out"); 985 } 986 count++; 987 988 // Using ByteBuffer for byte[] equality semantics 989 pair = groupOrSplitPhase(conn, tableName, pool, queue, startEndKeys); 990 Multimap<ByteBuffer, LoadQueueItem> regionGroups = pair.getFirst(); 991 992 if (!checkHFilesCountPerRegionPerFamily(regionGroups)) { 993 // Error is logged inside checkHFilesCountPerRegionPerFamily. 994 throw new IOException("Trying to load more than " + maxFilesPerRegionPerFamily 995 + " hfiles to one family of one region"); 996 } 997 998 bulkLoadPhase(conn, tableName, queue, regionGroups, copyFile, item2RegionMap); 999 1000 // NOTE: The next iteration's split / group could happen in parallel to 1001 // atomic bulkloads assuming that there are splits and no merges, and 1002 // that we can atomically pull out the groups we want to retry. 1003 } 1004 1005 return item2RegionMap; 1006 } 1007 1008 private void cleanup(AsyncClusterConnection conn, TableName tableName, Deque<LoadQueueItem> queue, 1009 ExecutorService pool) throws IOException { 1010 fsDelegationToken.releaseDelegationToken(); 1011 if (bulkToken != null) { 1012 conn.cleanupBulkLoad(tableName, bulkToken); 1013 } 1014 if (pool != null) { 1015 pool.shutdown(); 1016 } 1017 if (!queue.isEmpty()) { 1018 StringBuilder err = new StringBuilder(); 1019 err.append("-------------------------------------------------\n"); 1020 err.append("Bulk load aborted with some files not yet loaded:\n"); 1021 err.append("-------------------------------------------------\n"); 1022 for (LoadQueueItem q : queue) { 1023 err.append(" ").append(q.getFilePath()).append('\n'); 1024 } 1025 LOG.error(err.toString()); 1026 } 1027 } 1028 1029 /** 1030 * Perform a bulk load of the given map of families to hfiles into the given pre-existing table. 1031 * This method is not threadsafe. 1032 * @param map map of family to List of hfiles 1033 * @param tableName table to load the hfiles 1034 * @param silence true to ignore unmatched column families 1035 * @param copyFile always copy hfiles if true 1036 */ 1037 private Map<LoadQueueItem, ByteBuffer> doBulkLoad(AsyncClusterConnection conn, 1038 TableName tableName, Map<byte[], List<Path>> map, boolean silence, boolean copyFile) 1039 throws IOException { 1040 tableExists(conn, tableName); 1041 // LQI queue does not need to be threadsafe -- all operations on this queue 1042 // happen in this thread 1043 Deque<LoadQueueItem> queue = new ArrayDeque<>(); 1044 ExecutorService pool = null; 1045 try { 1046 prepareHFileQueue(conn, tableName, map, queue, silence); 1047 if (queue.isEmpty()) { 1048 LOG.warn("Bulk load operation did not get any files to load"); 1049 return Collections.emptyMap(); 1050 } 1051 pool = createExecutorService(); 1052 return performBulkLoad(conn, tableName, queue, pool, copyFile); 1053 } finally { 1054 cleanup(conn, tableName, queue, pool); 1055 } 1056 } 1057 1058 /** 1059 * Perform a bulk load of the given directory into the given pre-existing table. This method is 1060 * not threadsafe. 1061 * @param tableName table to load the hfiles 1062 * @param hfofDir the directory that was provided as the output path of a job using 1063 * HFileOutputFormat 1064 * @param silence true to ignore unmatched column families 1065 * @param copyFile always copy hfiles if true 1066 */ 1067 private Map<LoadQueueItem, ByteBuffer> doBulkLoad(AsyncClusterConnection conn, 1068 TableName tableName, Path hfofDir, boolean silence, boolean copyFile) throws IOException { 1069 tableExists(conn, tableName); 1070 1071 /* 1072 * Checking hfile format is a time-consuming operation, we should have an option to skip this 1073 * step when bulkloading millions of HFiles. See HBASE-13985. 1074 */ 1075 boolean validateHFile = getConf().getBoolean(VALIDATE_HFILES, true); 1076 if (!validateHFile) { 1077 LOG.warn("You are skipping HFiles validation, it might cause some data loss if files " 1078 + "are not correct. If you fail to read data from your table after using this " 1079 + "option, consider removing the files and bulkload again without this option. " 1080 + "See HBASE-13985"); 1081 } 1082 // LQI queue does not need to be threadsafe -- all operations on this queue 1083 // happen in this thread 1084 Deque<LoadQueueItem> queue = new ArrayDeque<>(); 1085 ExecutorService pool = null; 1086 try { 1087 prepareHFileQueue(getConf(), conn, tableName, hfofDir, queue, validateHFile, silence); 1088 1089 if (queue.isEmpty()) { 1090 LOG.warn( 1091 "Bulk load operation did not find any files to load in directory {}. " 1092 + "Does it contain files in subdirectories that correspond to column family names?", 1093 (hfofDir != null ? hfofDir.toUri().toString() : "")); 1094 return Collections.emptyMap(); 1095 } 1096 pool = createExecutorService(); 1097 return performBulkLoad(conn, tableName, queue, pool, copyFile); 1098 } finally { 1099 cleanup(conn, tableName, queue, pool); 1100 } 1101 } 1102 1103 @Override 1104 public Map<LoadQueueItem, ByteBuffer> bulkLoad(TableName tableName, 1105 Map<byte[], List<Path>> family2Files) throws IOException { 1106 try (AsyncClusterConnection conn = ClusterConnectionFactory 1107 .createAsyncClusterConnection(getConf(), null, userProvider.getCurrent())) { 1108 return doBulkLoad(conn, tableName, family2Files, isSilence(), isAlwaysCopyFiles()); 1109 } 1110 } 1111 1112 @Override 1113 public Map<LoadQueueItem, ByteBuffer> bulkLoad(TableName tableName, Path dir) throws IOException { 1114 try (AsyncClusterConnection conn = ClusterConnectionFactory 1115 .createAsyncClusterConnection(getConf(), null, userProvider.getCurrent())) { 1116 AsyncAdmin admin = conn.getAdmin(); 1117 if (!FutureUtils.get(admin.tableExists(tableName))) { 1118 if (isCreateTable()) { 1119 createTable(tableName, dir, admin); 1120 } else { 1121 throwAndLogTableNotFoundException(tableName); 1122 } 1123 } 1124 return doBulkLoad(conn, tableName, dir, isSilence(), isAlwaysCopyFiles()); 1125 } 1126 } 1127 1128 /** 1129 * @throws TableNotFoundException if table does not exist. 1130 */ 1131 private void tableExists(AsyncClusterConnection conn, TableName tableName) throws IOException { 1132 if (!FutureUtils.get(conn.getAdmin().tableExists(tableName))) { 1133 throwAndLogTableNotFoundException(tableName); 1134 } 1135 } 1136 1137 private void throwAndLogTableNotFoundException(TableName tn) throws TableNotFoundException { 1138 String errorMsg = format("Table '%s' does not exist.", tn); 1139 LOG.error(errorMsg); 1140 throw new TableNotFoundException(errorMsg); 1141 } 1142 1143 public void setBulkToken(String bulkToken) { 1144 this.bulkToken = bulkToken; 1145 } 1146 1147 public void setClusterIds(List<String> clusterIds) { 1148 this.clusterIds = clusterIds; 1149 } 1150 1151 private void usage() { 1152 System.err.println("Usage: " + "bin/hbase completebulkload [OPTIONS] " 1153 + "</PATH/TO/HFILEOUTPUTFORMAT-OUTPUT> <TABLENAME>\n" 1154 + "Loads directory of hfiles -- a region dir or product of HFileOutputFormat -- " 1155 + "into an hbase table.\n" + "OPTIONS (for other -D options, see source code):\n" + " -D" 1156 + CREATE_TABLE_CONF_KEY + "=no whether to create table; when 'no', target " 1157 + "table must exist.\n" + " -D" + IGNORE_UNMATCHED_CF_CONF_KEY 1158 + "=yes to ignore unmatched column families.\n" 1159 + " -loadTable for when directory of files to load has a depth of 3; target table must " 1160 + "exist;\n" + " must be last of the options on command line.\n" 1161 + "See https://hbase.apache.org/docs/architecture/bulk-loading#adopting-stray-data for " 1162 + "documentation.\n"); 1163 } 1164 1165 @Override 1166 public int run(String[] args) throws Exception { 1167 if (args.length != 2 && args.length != 3) { 1168 usage(); 1169 return -1; 1170 } 1171 // Re-initialize to apply -D options from the command line parameters 1172 initialize(); 1173 Path dirPath = new Path(args[0]); 1174 TableName tableName = TableName.valueOf(args[1]); 1175 if (args.length == 2) { 1176 return !bulkLoad(tableName, dirPath).isEmpty() ? 0 : -1; 1177 } else { 1178 Map<byte[], List<Path>> family2Files = Maps.newHashMap(); 1179 FileSystem fs = FileSystem.get(getConf()); 1180 for (FileStatus regionDir : fs.listStatus(dirPath)) { 1181 FSVisitor.visitRegionStoreFiles(fs, regionDir.getPath(), (region, family, hfileName) -> { 1182 Path path = new Path(regionDir.getPath(), new Path(family, hfileName)); 1183 byte[] familyName = Bytes.toBytes(family); 1184 if (family2Files.containsKey(familyName)) { 1185 family2Files.get(familyName).add(path); 1186 } else { 1187 family2Files.put(familyName, Lists.newArrayList(path)); 1188 } 1189 }); 1190 } 1191 return !bulkLoad(tableName, family2Files).isEmpty() ? 0 : -1; 1192 } 1193 } 1194 1195 public static void main(String[] args) throws Exception { 1196 Configuration conf = HBaseConfiguration.create(); 1197 int ret = ToolRunner.run(conf, new BulkLoadHFilesTool(conf), args); 1198 System.exit(ret); 1199 } 1200 1201 @Override 1202 public void disableReplication() { 1203 this.replicate = false; 1204 } 1205 1206 @Override 1207 public boolean isReplicationDisabled() { 1208 return !this.replicate; 1209 } 1210}