1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.wal;
20
21 import java.io.EOFException;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InterruptedIOException;
25 import java.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.LinkedList;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.NavigableSet;
34 import java.util.Set;
35 import java.util.TreeMap;
36 import java.util.TreeSet;
37 import java.util.UUID;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.CompletionService;
40 import java.util.concurrent.ConcurrentHashMap;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.ExecutorCompletionService;
43 import java.util.concurrent.Future;
44 import java.util.concurrent.ThreadFactory;
45 import java.util.concurrent.ThreadPoolExecutor;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.atomic.AtomicBoolean;
48 import java.util.concurrent.atomic.AtomicLong;
49 import java.util.concurrent.atomic.AtomicReference;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52
53 import org.apache.commons.logging.Log;
54 import org.apache.commons.logging.LogFactory;
55 import org.apache.hadoop.conf.Configuration;
56 import org.apache.hadoop.fs.FileAlreadyExistsException;
57 import org.apache.hadoop.fs.FileStatus;
58 import org.apache.hadoop.fs.FileSystem;
59 import org.apache.hadoop.fs.Path;
60 import org.apache.hadoop.fs.PathFilter;
61 import org.apache.hadoop.hbase.Cell;
62 import org.apache.hadoop.hbase.CellScanner;
63 import org.apache.hadoop.hbase.CellUtil;
64 import org.apache.hadoop.hbase.CoordinatedStateException;
65 import org.apache.hadoop.hbase.CoordinatedStateManager;
66 import org.apache.hadoop.hbase.HBaseConfiguration;
67 import org.apache.hadoop.hbase.HConstants;
68 import org.apache.hadoop.hbase.HRegionInfo;
69 import org.apache.hadoop.hbase.HRegionLocation;
70 import org.apache.hadoop.hbase.RemoteExceptionHandler;
71 import org.apache.hadoop.hbase.ServerName;
72 import org.apache.hadoop.hbase.TableName;
73 import org.apache.hadoop.hbase.TableNotFoundException;
74 import org.apache.hadoop.hbase.TableStateManager;
75 import org.apache.hadoop.hbase.classification.InterfaceAudience;
76 import org.apache.hadoop.hbase.client.ConnectionUtils;
77 import org.apache.hadoop.hbase.client.Delete;
78 import org.apache.hadoop.hbase.client.Durability;
79 import org.apache.hadoop.hbase.client.HConnection;
80 import org.apache.hadoop.hbase.client.HConnectionManager;
81 import org.apache.hadoop.hbase.client.Mutation;
82 import org.apache.hadoop.hbase.client.Put;
83 import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
84 import org.apache.hadoop.hbase.coordination.ZKSplitLogManagerCoordination;
85 import org.apache.hadoop.hbase.exceptions.RegionOpeningException;
86 import org.apache.hadoop.hbase.io.HeapSize;
87 import org.apache.hadoop.hbase.master.SplitLogManager;
88 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
89 import org.apache.hadoop.hbase.monitoring.TaskMonitor;
90 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
91 import org.apache.hadoop.hbase.protobuf.RequestConverter;
92 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService.BlockingInterface;
93 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
94 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
95 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WALEntry;
96 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
97 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
98 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
99 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
100 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
101 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
102 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
103 import org.apache.hadoop.hbase.regionserver.HRegion;
104 import org.apache.hadoop.hbase.regionserver.LastSequenceId;
105
106 import org.apache.hadoop.hbase.regionserver.wal.FSHLog;
107 import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
108 import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
109 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
110 import org.apache.hadoop.hbase.regionserver.wal.WALEditsReplaySink;
111 import org.apache.hadoop.hbase.util.Bytes;
112 import org.apache.hadoop.hbase.util.CancelableProgressable;
113 import org.apache.hadoop.hbase.util.ClassSize;
114 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
115 import org.apache.hadoop.hbase.util.FSUtils;
116 import org.apache.hadoop.hbase.util.Pair;
117 import org.apache.hadoop.hbase.util.Threads;
118 import org.apache.hadoop.hbase.wal.WAL.Entry;
119 import org.apache.hadoop.hbase.wal.WAL.Reader;
120 import org.apache.hadoop.hbase.wal.WALProvider.Writer;
121 import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
122 import org.apache.hadoop.io.MultipleIOException;
123
124 import com.google.common.annotations.VisibleForTesting;
125 import com.google.common.base.Preconditions;
126 import com.google.common.collect.Lists;
127 import com.google.protobuf.ServiceException;
128 import com.google.protobuf.TextFormat;
129
130
131
132
133
134
135 @InterfaceAudience.Private
136 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="JLM_JSR166_UTILCONCURRENT_MONITORENTER",
137 justification="Synchronization on concurrent map is intended")
138 public class WALSplitter {
139 private static final Log LOG = LogFactory.getLog(WALSplitter.class);
140
141
142 public static final boolean SPLIT_SKIP_ERRORS_DEFAULT = false;
143
144
145 protected final Path walDir;
146 protected final FileSystem walFS;
147 protected final Configuration conf;
148
149
150
151 PipelineController controller;
152 OutputSink outputSink;
153 EntryBuffers entryBuffers;
154
155 private Set<TableName> disablingOrDisabledTables =
156 new HashSet<TableName>();
157 private BaseCoordinatedStateManager csm;
158 private final WALFactory walFactory;
159
160 private MonitoredTask status;
161
162
163 protected final LastSequenceId sequenceIdChecker;
164
165 protected boolean distributedLogReplay;
166
167 private final boolean splitWriterCreationBounded;
168
169
170
171 protected Map<String, Long> lastFlushedSequenceIds = new ConcurrentHashMap<String, Long>();
172
173
174 protected Map<String, Map<byte[], Long>> regionMaxSeqIdInStores =
175 new ConcurrentHashMap<String, Map<byte[], Long>>();
176
177
178 protected String failedServerName = "";
179
180
181 private final int numWriterThreads;
182
183
184 private final int minBatchSize;
185
186
187 private FileStatus fileBeingSplit;
188
189 public final static String SPLIT_WRITER_CREATION_BOUNDED = "hbase.split.writer.creation.bounded";
190
191 @VisibleForTesting
192 WALSplitter(final WALFactory factory, Configuration conf, Path walDir,
193 FileSystem walFS, LastSequenceId idChecker,
194 CoordinatedStateManager csm, RecoveryMode mode) {
195 this.conf = HBaseConfiguration.create(conf);
196 String codecClassName = conf
197 .get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
198 this.conf.set(HConstants.RPC_CODEC_CONF_KEY, codecClassName);
199 this.walDir = walDir;
200 this.walFS = walFS;
201 this.sequenceIdChecker = idChecker;
202 this.csm = (BaseCoordinatedStateManager)csm;
203 this.walFactory = factory;
204 this.controller = new PipelineController();
205 this.splitWriterCreationBounded = conf.getBoolean(SPLIT_WRITER_CREATION_BOUNDED, false);
206 entryBuffers = new EntryBuffers(controller,
207 this.conf.getInt("hbase.regionserver.hlog.splitlog.buffersize",
208 128*1024*1024), splitWriterCreationBounded);
209
210
211
212 this.minBatchSize = this.conf.getInt("hbase.regionserver.wal.logreplay.batch.size", 64);
213 this.distributedLogReplay = (RecoveryMode.LOG_REPLAY == mode);
214
215 this.numWriterThreads = this.conf.getInt("hbase.regionserver.hlog.splitlog.writer.threads", 3);
216 if (csm != null && this.distributedLogReplay) {
217 outputSink = new LogReplayOutputSink(controller, entryBuffers, numWriterThreads);
218 } else {
219 if (this.distributedLogReplay) {
220 LOG.info("ZooKeeperWatcher is passed in as NULL so disable distrubitedLogRepaly.");
221 }
222 this.distributedLogReplay = false;
223 if(splitWriterCreationBounded){
224 outputSink = new BoundedLogWriterCreationOutputSink(controller,
225 entryBuffers, numWriterThreads);
226 }else {
227 outputSink = new LogRecoveredEditsOutputSink(controller, entryBuffers, numWriterThreads);
228 }
229 }
230
231 }
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249 public static boolean splitLogFile(Path walDir, FileStatus logfile, FileSystem walFS,
250 Configuration conf, CancelableProgressable reporter, LastSequenceId idChecker,
251 CoordinatedStateManager cp, RecoveryMode mode, final WALFactory factory) throws IOException {
252 WALSplitter s = new WALSplitter(factory, conf, walDir, walFS, idChecker, cp, mode);
253 return s.splitLogFile(logfile, reporter);
254 }
255
256
257
258
259
260 public static List<Path> split(Path walRootDir, Path logDir, Path oldLogDir,
261 FileSystem walFs, Configuration conf, final WALFactory factory) throws IOException {
262 final FileStatus[] logfiles = SplitLogManager.getFileList(conf,
263 Collections.singletonList(logDir), null);
264 List<Path> splits = new ArrayList<Path>();
265 if (logfiles != null && logfiles.length > 0) {
266 for (FileStatus logfile: logfiles) {
267 WALSplitter s = new WALSplitter(factory, conf, walRootDir, walFs, null, null,
268 RecoveryMode.LOG_SPLITTING);
269 if (s.splitLogFile(logfile, null)) {
270 finishSplitLogFile(walRootDir, oldLogDir, logfile.getPath(), conf);
271 if (s.outputSink.splits != null) {
272 splits.addAll(s.outputSink.splits);
273 }
274 }
275 }
276 }
277 if (!walFs.delete(logDir, true)) {
278 throw new IOException("Unable to delete src dir: " + logDir);
279 }
280 return splits;
281 }
282
283
284
285
286
287 @VisibleForTesting
288 boolean splitLogFile(FileStatus logfile, CancelableProgressable reporter) throws IOException {
289 Preconditions.checkState(status == null);
290 Preconditions.checkArgument(logfile.isFile(),
291 "passed in file status is for something other than a regular file.");
292 boolean isCorrupted = false;
293 boolean skipErrors = conf.getBoolean("hbase.hlog.split.skip.errors",
294 SPLIT_SKIP_ERRORS_DEFAULT);
295 int interval = conf.getInt("hbase.splitlog.report.interval.loglines", 1024);
296 Path logPath = logfile.getPath();
297 boolean outputSinkStarted = false;
298 boolean progress_failed = false;
299 int editsCount = 0;
300 int editsSkipped = 0;
301
302 status =
303 TaskMonitor.get().createStatus(
304 "Splitting log file " + logfile.getPath() + "into a temporary staging area.");
305 Reader in = null;
306 this.fileBeingSplit = logfile;
307 try {
308 long logLength = logfile.getLen();
309 LOG.info("Splitting wal: " + logPath + ", length=" + logLength);
310 LOG.info("DistributedLogReplay = " + this.distributedLogReplay);
311 status.setStatus("Opening log file");
312 if (reporter != null && !reporter.progress()) {
313 progress_failed = true;
314 return false;
315 }
316 try {
317 in = getReader(logfile, skipErrors, reporter);
318 } catch (CorruptedLogFileException e) {
319 LOG.warn("Could not get reader, corrupted log file " + logPath, e);
320 ZKSplitLog.markCorrupted(walDir, logfile.getPath().getName(), walFS);
321 isCorrupted = true;
322 }
323 if (in == null) {
324 LOG.warn("Nothing to split in log file " + logPath);
325 return true;
326 }
327 if (csm != null) {
328 try {
329 TableStateManager tsm = csm.getTableStateManager();
330 disablingOrDisabledTables = tsm.getTablesInStates(
331 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING);
332 } catch (CoordinatedStateException e) {
333 throw new IOException("Can't get disabling/disabled tables", e);
334 }
335 }
336 int numOpenedFilesBeforeReporting = conf.getInt("hbase.splitlog.report.openedfiles", 3);
337 int numOpenedFilesLastCheck = 0;
338 outputSink.setReporter(reporter);
339 outputSink.startWriterThreads();
340 outputSinkStarted = true;
341 Entry entry;
342 Long lastFlushedSequenceId = -1L;
343 ServerName serverName = DefaultWALProvider.getServerNameFromWALDirectoryName(logPath);
344 failedServerName = (serverName == null) ? "" : serverName.getServerName();
345 while ((entry = getNextLogLine(in, logPath, skipErrors)) != null) {
346 byte[] region = entry.getKey().getEncodedRegionName();
347 String encodedRegionNameAsStr = Bytes.toString(region);
348 lastFlushedSequenceId = lastFlushedSequenceIds.get(encodedRegionNameAsStr);
349 if (lastFlushedSequenceId == null) {
350 if (this.distributedLogReplay) {
351 RegionStoreSequenceIds ids =
352 csm.getSplitLogWorkerCoordination().getRegionFlushedSequenceId(failedServerName,
353 encodedRegionNameAsStr);
354 if (ids != null) {
355 lastFlushedSequenceId = ids.getLastFlushedSequenceId();
356 if (LOG.isDebugEnabled()) {
357 LOG.debug("DLR Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
358 TextFormat.shortDebugString(ids));
359 }
360 }
361 } else if (sequenceIdChecker != null) {
362 RegionStoreSequenceIds ids = sequenceIdChecker.getLastSequenceId(region);
363 Map<byte[], Long> maxSeqIdInStores = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
364 for (StoreSequenceId storeSeqId : ids.getStoreSequenceIdList()) {
365 maxSeqIdInStores.put(storeSeqId.getFamilyName().toByteArray(),
366 storeSeqId.getSequenceId());
367 }
368 regionMaxSeqIdInStores.put(encodedRegionNameAsStr, maxSeqIdInStores);
369 lastFlushedSequenceId = ids.getLastFlushedSequenceId();
370 if (LOG.isDebugEnabled()) {
371 LOG.debug("DLS Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
372 TextFormat.shortDebugString(ids));
373 }
374 }
375 if (lastFlushedSequenceId == null) {
376 lastFlushedSequenceId = -1L;
377 }
378 lastFlushedSequenceIds.put(encodedRegionNameAsStr, lastFlushedSequenceId);
379 }
380 if (lastFlushedSequenceId >= entry.getKey().getLogSeqNum()) {
381 editsSkipped++;
382 continue;
383 }
384
385 if (entry.getEdit().isMetaEdit() && !outputSink.keepRegionEvent(entry)) {
386 editsSkipped++;
387 continue;
388 }
389 entryBuffers.appendEntry(entry);
390 editsCount++;
391 int moreWritersFromLastCheck = this.getNumOpenWriters() - numOpenedFilesLastCheck;
392
393 if (editsCount % interval == 0
394 || moreWritersFromLastCheck > numOpenedFilesBeforeReporting) {
395 numOpenedFilesLastCheck = this.getNumOpenWriters();
396 String countsStr = (editsCount - (editsSkipped + outputSink.getSkippedEdits()))
397 + " edits, skipped " + editsSkipped + " edits.";
398 status.setStatus("Split " + countsStr);
399 if (reporter != null && !reporter.progress()) {
400 progress_failed = true;
401 return false;
402 }
403 }
404 }
405 } catch (InterruptedException ie) {
406 IOException iie = new InterruptedIOException();
407 iie.initCause(ie);
408 throw iie;
409 } catch (CorruptedLogFileException e) {
410 LOG.warn("Could not parse, corrupted log file " + logPath, e);
411 csm.getSplitLogWorkerCoordination().markCorrupted(walDir,
412 logfile.getPath().getName(), walFS);
413 isCorrupted = true;
414 } catch (IOException e) {
415 e = RemoteExceptionHandler.checkIOException(e);
416 throw e;
417 } finally {
418 LOG.debug("Finishing writing output logs and closing down.");
419 try {
420 if (null != in) {
421 in.close();
422 }
423 } catch (IOException exception) {
424 LOG.warn("Could not close wal reader: " + exception.getMessage());
425 LOG.debug("exception details", exception);
426 }
427 try {
428 if (outputSinkStarted) {
429
430
431 progress_failed = true;
432 progress_failed = outputSink.finishWritingAndClose() == null;
433 }
434 } finally {
435 String msg =
436 "Processed " + editsCount + " edits across " + outputSink.getNumberOfRecoveredRegions()
437 + " regions; edits skipped=" + editsSkipped + "; log file=" + logPath +
438 ", length=" + logfile.getLen() +
439 ", corrupted=" + isCorrupted + ", progress failed=" + progress_failed;
440 LOG.info(msg);
441 status.markComplete(msg);
442 }
443 }
444 return !progress_failed;
445 }
446
447
448
449
450
451
452
453
454
455
456
457
458 public static void finishSplitLogFile(String logfile,
459 Configuration conf) throws IOException {
460 Path walDir = FSUtils.getWALRootDir(conf);
461 Path oldLogDir = new Path(walDir, HConstants.HREGION_OLDLOGDIR_NAME);
462 Path logPath;
463 if (FSUtils.isStartingWithPath(walDir, logfile)) {
464 logPath = new Path(logfile);
465 } else {
466 logPath = new Path(walDir, logfile);
467 }
468 finishSplitLogFile(walDir, oldLogDir, logPath, conf);
469 }
470
471 private static void finishSplitLogFile(Path walDir, Path oldLogDir,
472 Path logPath, Configuration conf) throws IOException {
473 List<Path> processedLogs = new ArrayList<Path>();
474 List<Path> corruptedLogs = new ArrayList<Path>();
475 FileSystem walFS = walDir.getFileSystem(conf);
476 if (ZKSplitLog.isCorrupted(walDir, logPath.getName(), walFS)) {
477 corruptedLogs.add(logPath);
478 } else {
479 processedLogs.add(logPath);
480 }
481 archiveLogs(corruptedLogs, processedLogs, oldLogDir, walFS, conf);
482 Path stagingDir = ZKSplitLog.getSplitLogDir(walDir, logPath.getName());
483 walFS.delete(stagingDir, true);
484 }
485
486
487
488
489
490
491
492
493
494
495
496
497
498 private static void archiveLogs(
499 final List<Path> corruptedLogs,
500 final List<Path> processedLogs, final Path oldLogDir,
501 final FileSystem walFS, final Configuration conf) throws IOException {
502 final Path corruptDir = new Path(FSUtils.getWALRootDir(conf), conf.get(
503 "hbase.regionserver.hlog.splitlog.corrupt.dir", HConstants.CORRUPT_DIR_NAME));
504
505 if (!walFS.mkdirs(corruptDir)) {
506 LOG.info("Unable to mkdir " + corruptDir);
507 }
508 walFS.mkdirs(oldLogDir);
509
510
511
512 for (Path corrupted : corruptedLogs) {
513 Path p = new Path(corruptDir, corrupted.getName());
514 if (walFS.exists(corrupted)) {
515 if (!walFS.rename(corrupted, p)) {
516 LOG.warn("Unable to move corrupted log " + corrupted + " to " + p);
517 } else {
518 LOG.warn("Moved corrupted log " + corrupted + " to " + p);
519 }
520 }
521 }
522
523 for (Path p : processedLogs) {
524 Path newPath = FSHLog.getWALArchivePath(oldLogDir, p);
525 if (walFS.exists(p)) {
526 if (!FSUtils.renameAndSetModifyTime(walFS, p, newPath)) {
527 LOG.warn("Unable to move " + p + " to " + newPath);
528 } else {
529 LOG.info("Archived processed log " + p + " to " + newPath);
530 }
531 }
532 }
533 }
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548 @SuppressWarnings("deprecation")
549 @VisibleForTesting
550 static Path getRegionSplitEditsPath(final Entry logEntry, String fileNameBeingSplit,
551 String tmpDirName, Configuration conf) throws IOException {
552 FileSystem walFS = FSUtils.getWALFileSystem(conf);
553 TableName tableName = logEntry.getKey().getTablename();
554 String encodedRegionName = Bytes.toString(logEntry.getKey().getEncodedRegionName());
555 Path regionDir = FSUtils.getWALRegionDir(conf, tableName, encodedRegionName);
556 Path dir = getRegionDirRecoveredEditsDir(regionDir);
557
558 if (walFS.exists(dir) && walFS.isFile(dir)) {
559 Path tmp = new Path(tmpDirName);
560 if (!walFS.exists(tmp)) {
561 walFS.mkdirs(tmp);
562 }
563 tmp = new Path(tmp, HConstants.RECOVERED_EDITS_DIR + "_" + encodedRegionName);
564 LOG.warn("Found existing old file: " + dir + ". It could be some "
565 + "leftover of an old installation. It should be a folder instead. "
566 + "So moving it to " + tmp);
567 if (!walFS.rename(dir, tmp)) {
568 LOG.warn("Failed to sideline old file " + dir);
569 }
570 }
571
572 if (!walFS.exists(dir) && !walFS.mkdirs(dir)) {
573 LOG.warn("mkdir failed on " + dir);
574 }
575
576
577
578 String fileName = formatRecoveredEditsFileName(logEntry.getKey().getLogSeqNum());
579 fileName = getTmpRecoveredEditsFileName(fileName + "-" + fileNameBeingSplit);
580 return new Path(dir, fileName);
581 }
582
583 private static String getTmpRecoveredEditsFileName(String fileName) {
584 return fileName + RECOVERED_LOG_TMPFILE_SUFFIX;
585 }
586
587
588
589
590
591
592
593
594
595 private static Path getCompletedRecoveredEditsFilePath(Path srcPath,
596 long maximumEditLogSeqNum) {
597 String fileName = formatRecoveredEditsFileName(maximumEditLogSeqNum);
598 return new Path(srcPath.getParent(), fileName);
599 }
600
601 @VisibleForTesting
602 static String formatRecoveredEditsFileName(final long seqid) {
603 return String.format("%019d", seqid);
604 }
605
606 private static final Pattern EDITFILES_NAME_PATTERN = Pattern.compile("-?[0-9]+");
607 private static final String RECOVERED_LOG_TMPFILE_SUFFIX = ".temp";
608
609
610
611
612
613
614
615 public static Path getRegionDirRecoveredEditsDir(final Path regionDir) {
616 return new Path(regionDir, HConstants.RECOVERED_EDITS_DIR);
617 }
618
619
620
621
622
623
624
625
626
627
628 public static NavigableSet<Path> getSplitEditFilesSorted(final FileSystem walFS,
629 final Path regionDir) throws IOException {
630 NavigableSet<Path> filesSorted = new TreeSet<Path>();
631 Path editsdir = getRegionDirRecoveredEditsDir(regionDir);
632 if (!walFS.exists(editsdir)) {
633 return filesSorted;
634 }
635 FileStatus[] files = FSUtils.listStatus(walFS, editsdir, new PathFilter() {
636 @Override
637 public boolean accept(Path p) {
638 boolean result = false;
639 try {
640
641
642
643
644 Matcher m = EDITFILES_NAME_PATTERN.matcher(p.getName());
645 result = walFS.isFile(p) && m.matches();
646
647
648 if (p.getName().endsWith(RECOVERED_LOG_TMPFILE_SUFFIX)) {
649 result = false;
650 }
651
652 if (isSequenceIdFile(p)) {
653 result = false;
654 }
655 } catch (IOException e) {
656 LOG.warn("Failed isFile check on " + p);
657 }
658 return result;
659 }
660 });
661 if (files == null) {
662 return filesSorted;
663 }
664 for (FileStatus status : files) {
665 filesSorted.add(status.getPath());
666 }
667 return filesSorted;
668 }
669
670
671
672
673
674
675
676
677
678
679 public static Path moveAsideBadEditsFile(final FileSystem walFS, final Path edits)
680 throws IOException {
681 Path moveAsideName = new Path(edits.getParent(), edits.getName() + "."
682 + System.currentTimeMillis());
683 if (!walFS.rename(edits, moveAsideName)) {
684 LOG.warn("Rename failed from " + edits + " to " + moveAsideName);
685 }
686 return moveAsideName;
687 }
688
689 private static final String SEQUENCE_ID_FILE_SUFFIX = ".seqid";
690 private static final String OLD_SEQUENCE_ID_FILE_SUFFIX = "_seqid";
691 private static final int SEQUENCE_ID_FILE_SUFFIX_LENGTH = SEQUENCE_ID_FILE_SUFFIX.length();
692
693
694
695
696 @VisibleForTesting
697 public static boolean isSequenceIdFile(final Path file) {
698 return file.getName().endsWith(SEQUENCE_ID_FILE_SUFFIX)
699 || file.getName().endsWith(OLD_SEQUENCE_ID_FILE_SUFFIX);
700 }
701
702
703
704
705
706
707
708
709
710
711 public static long writeRegionSequenceIdFile(final FileSystem walFS, final Path regionDir,
712 long newSeqId, long saftyBumper) throws IOException {
713
714 Path editsdir = WALSplitter.getRegionDirRecoveredEditsDir(regionDir);
715 long maxSeqId = 0;
716 FileStatus[] files = null;
717 if (walFS.exists(editsdir)) {
718 files = FSUtils.listStatus(walFS, editsdir, new PathFilter() {
719 @Override
720 public boolean accept(Path p) {
721 return isSequenceIdFile(p);
722 }
723 });
724 if (files != null) {
725 for (FileStatus status : files) {
726 String fileName = status.getPath().getName();
727 try {
728 Long tmpSeqId = Long.parseLong(fileName.substring(0, fileName.length()
729 - SEQUENCE_ID_FILE_SUFFIX_LENGTH));
730 maxSeqId = Math.max(tmpSeqId, maxSeqId);
731 } catch (NumberFormatException ex) {
732 LOG.warn("Invalid SeqId File Name=" + fileName);
733 }
734 }
735 }
736 }
737 if (maxSeqId > newSeqId) {
738 newSeqId = maxSeqId;
739 }
740 newSeqId += saftyBumper;
741
742
743 Path newSeqIdFile = new Path(editsdir, newSeqId + SEQUENCE_ID_FILE_SUFFIX);
744 if (newSeqId != maxSeqId) {
745 try {
746 if (!walFS.createNewFile(newSeqIdFile) && !walFS.exists(newSeqIdFile)) {
747 throw new IOException("Failed to create SeqId file:" + newSeqIdFile);
748 }
749 if (LOG.isDebugEnabled()) {
750 LOG.debug("Wrote region seqId=" + newSeqIdFile + " to file, newSeqId=" + newSeqId
751 + ", maxSeqId=" + maxSeqId);
752 }
753 } catch (FileAlreadyExistsException ignored) {
754
755 }
756 }
757
758 if (files != null) {
759 for (FileStatus status : files) {
760 if (newSeqIdFile.equals(status.getPath())) {
761 continue;
762 }
763 walFS.delete(status.getPath(), false);
764 }
765 }
766 return newSeqId;
767 }
768
769
770
771
772
773
774
775
776
777 protected Reader getReader(FileStatus file, boolean skipErrors, CancelableProgressable reporter)
778 throws IOException, CorruptedLogFileException {
779 Path path = file.getPath();
780 long length = file.getLen();
781 Reader in;
782
783
784
785
786 if (length <= 0) {
787 LOG.warn("File " + path + " might be still open, length is 0");
788 }
789
790 try {
791 FSUtils.getInstance(walFS, conf).recoverFileLease(walFS, path, conf, reporter);
792 try {
793 in = getReader(path, reporter);
794 } catch (EOFException e) {
795 if (length <= 0) {
796
797
798
799
800
801 LOG.warn("Could not open " + path + " for reading. File is empty", e);
802 return null;
803 } else {
804
805 return null;
806 }
807 }
808 } catch (IOException e) {
809 if (e instanceof FileNotFoundException) {
810
811 LOG.warn("File " + path + " doesn't exist anymore.", e);
812 return null;
813 }
814 if (!skipErrors || e instanceof InterruptedIOException) {
815 throw e;
816 }
817 CorruptedLogFileException t =
818 new CorruptedLogFileException("skipErrors=true Could not open wal " +
819 path + " ignoring");
820 t.initCause(e);
821 throw t;
822 }
823 return in;
824 }
825
826 static private Entry getNextLogLine(Reader in, Path path, boolean skipErrors)
827 throws CorruptedLogFileException, IOException {
828 try {
829 return in.next();
830 } catch (EOFException eof) {
831
832 LOG.info("EOF from wal " + path + ". continuing");
833 return null;
834 } catch (IOException e) {
835
836
837 if (e.getCause() != null &&
838 (e.getCause() instanceof ParseException ||
839 e.getCause() instanceof org.apache.hadoop.fs.ChecksumException)) {
840 LOG.warn("Parse exception " + e.getCause().toString() + " from wal "
841 + path + ". continuing");
842 return null;
843 }
844 if (!skipErrors) {
845 throw e;
846 }
847 CorruptedLogFileException t =
848 new CorruptedLogFileException("skipErrors=true Ignoring exception" +
849 " while parsing wal " + path + ". Marking as corrupted");
850 t.initCause(e);
851 throw t;
852 }
853 }
854
855
856
857
858
859 protected Writer createWriter(Path logfile)
860 throws IOException {
861 return walFactory.createRecoveredEditsWriter(walFS, logfile);
862 }
863
864
865
866
867
868 protected Reader getReader(Path curLogFile, CancelableProgressable reporter) throws IOException {
869 return walFactory.createReader(walFS, curLogFile, reporter);
870 }
871
872
873
874
875 private int getNumOpenWriters() {
876 int result = 0;
877 if (this.outputSink != null) {
878 result += this.outputSink.getNumOpenWriters();
879 }
880 return result;
881 }
882
883
884
885
886 public static class PipelineController {
887
888
889 AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
890
891
892
893 public final Object dataAvailable = new Object();
894
895 void writerThreadError(Throwable t) {
896 thrown.compareAndSet(null, t);
897 }
898
899
900
901
902 void checkForErrors() throws IOException {
903 Throwable thrown = this.thrown.get();
904 if (thrown == null) return;
905 if (thrown instanceof IOException) {
906 throw new IOException(thrown);
907 } else {
908 throw new RuntimeException(thrown);
909 }
910 }
911 }
912
913
914
915
916
917
918
919
920 public static class EntryBuffers {
921 PipelineController controller;
922
923 Map<byte[], RegionEntryBuffer> buffers =
924 new TreeMap<byte[], RegionEntryBuffer>(Bytes.BYTES_COMPARATOR);
925
926
927
928
929 Set<byte[]> currentlyWriting = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
930
931 long totalBuffered = 0;
932 final long maxHeapUsage;
933 boolean splitWriterCreationBounded;
934
935
936 public EntryBuffers(PipelineController controller, long maxHeapUsage) {
937 this(controller, maxHeapUsage, false);
938 }
939
940 public EntryBuffers(PipelineController controller, long maxHeapUsage,
941 boolean splitWriterCreationBounded) {
942 this.controller = controller;
943 this.maxHeapUsage = maxHeapUsage;
944 this.splitWriterCreationBounded = splitWriterCreationBounded;
945 }
946
947
948
949
950
951
952
953
954 public void appendEntry(Entry entry) throws InterruptedException, IOException {
955 WALKey key = entry.getKey();
956
957 RegionEntryBuffer buffer;
958 long incrHeap;
959 synchronized (this) {
960 buffer = buffers.get(key.getEncodedRegionName());
961 if (buffer == null) {
962 buffer = new RegionEntryBuffer(key.getTablename(), key.getEncodedRegionName());
963 buffers.put(key.getEncodedRegionName(), buffer);
964 }
965 incrHeap= buffer.appendEntry(entry);
966 }
967
968
969 synchronized (controller.dataAvailable) {
970 totalBuffered += incrHeap;
971 while (totalBuffered > maxHeapUsage && controller.thrown.get() == null) {
972 LOG.debug("Used " + totalBuffered + " bytes of buffered edits, waiting for IO threads...");
973 controller.dataAvailable.wait(2000);
974 }
975 controller.dataAvailable.notifyAll();
976 }
977 controller.checkForErrors();
978 }
979
980
981
982
983 synchronized RegionEntryBuffer getChunkToWrite() {
984
985
986
987
988 if(splitWriterCreationBounded && totalBuffered < maxHeapUsage){
989 return null;
990 }
991
992 long biggestSize = 0;
993 byte[] biggestBufferKey = null;
994
995 for (Map.Entry<byte[], RegionEntryBuffer> entry : buffers.entrySet()) {
996 long size = entry.getValue().heapSize();
997 if (size > biggestSize && (!currentlyWriting.contains(entry.getKey()))) {
998 biggestSize = size;
999 biggestBufferKey = entry.getKey();
1000 }
1001 }
1002 if (biggestBufferKey == null) {
1003 return null;
1004 }
1005
1006 RegionEntryBuffer buffer = buffers.remove(biggestBufferKey);
1007 currentlyWriting.add(biggestBufferKey);
1008 return buffer;
1009 }
1010
1011 void doneWriting(RegionEntryBuffer buffer) {
1012 synchronized (this) {
1013 boolean removed = currentlyWriting.remove(buffer.encodedRegionName);
1014 assert removed;
1015 }
1016 long size = buffer.heapSize();
1017
1018 synchronized (controller.dataAvailable) {
1019 totalBuffered -= size;
1020
1021 controller.dataAvailable.notifyAll();
1022 }
1023 }
1024
1025 synchronized boolean isRegionCurrentlyWriting(byte[] region) {
1026 return currentlyWriting.contains(region);
1027 }
1028
1029 public void waitUntilDrained() {
1030 synchronized (controller.dataAvailable) {
1031 while (totalBuffered > 0) {
1032 try {
1033 controller.dataAvailable.wait(2000);
1034 } catch (InterruptedException e) {
1035 LOG.warn("Got interrupted while waiting for EntryBuffers is drained");
1036 Thread.interrupted();
1037 break;
1038 }
1039 }
1040 }
1041 }
1042 }
1043
1044
1045
1046
1047
1048
1049
1050 public static class RegionEntryBuffer implements HeapSize {
1051 long heapInBuffer = 0;
1052 List<Entry> entryBuffer;
1053 TableName tableName;
1054 byte[] encodedRegionName;
1055
1056 RegionEntryBuffer(TableName tableName, byte[] region) {
1057 this.tableName = tableName;
1058 this.encodedRegionName = region;
1059 this.entryBuffer = new LinkedList<Entry>();
1060 }
1061
1062 long appendEntry(Entry entry) {
1063 internify(entry);
1064 entryBuffer.add(entry);
1065 long incrHeap = entry.getEdit().heapSize() +
1066 ClassSize.align(2 * ClassSize.REFERENCE) +
1067 0;
1068 heapInBuffer += incrHeap;
1069 return incrHeap;
1070 }
1071
1072 private void internify(Entry entry) {
1073 WALKey k = entry.getKey();
1074 k.internTableName(this.tableName);
1075 k.internEncodedRegionName(this.encodedRegionName);
1076 }
1077
1078 @Override
1079 public long heapSize() {
1080 return heapInBuffer;
1081 }
1082
1083 public byte[] getEncodedRegionName() {
1084 return encodedRegionName;
1085 }
1086
1087 public List<Entry> getEntryBuffer() {
1088 return entryBuffer;
1089 }
1090
1091 public TableName getTableName() {
1092 return tableName;
1093 }
1094 }
1095
1096 public static class WriterThread extends Thread {
1097 private volatile boolean shouldStop = false;
1098 private PipelineController controller;
1099 private EntryBuffers entryBuffers;
1100 private OutputSink outputSink = null;
1101
1102 WriterThread(PipelineController controller, EntryBuffers entryBuffers, OutputSink sink, int i){
1103 super(Thread.currentThread().getName() + "-Writer-" + i);
1104 this.controller = controller;
1105 this.entryBuffers = entryBuffers;
1106 outputSink = sink;
1107 }
1108
1109 @Override
1110 public void run() {
1111 try {
1112 doRun();
1113 } catch (Throwable t) {
1114 LOG.error("Exiting thread", t);
1115 controller.writerThreadError(t);
1116 }
1117 }
1118
1119 private void doRun() throws IOException {
1120 if (LOG.isTraceEnabled()) LOG.trace("Writer thread starting");
1121 while (true) {
1122 RegionEntryBuffer buffer = entryBuffers.getChunkToWrite();
1123 if (buffer == null) {
1124
1125 synchronized (controller.dataAvailable) {
1126 if (shouldStop && !this.outputSink.flush()) {
1127 return;
1128 }
1129 try {
1130 controller.dataAvailable.wait(500);
1131 } catch (InterruptedException ie) {
1132 if (!shouldStop) {
1133 throw new RuntimeException(ie);
1134 }
1135 }
1136 }
1137 continue;
1138 }
1139
1140 assert buffer != null;
1141 try {
1142 writeBuffer(buffer);
1143 } finally {
1144 entryBuffers.doneWriting(buffer);
1145 }
1146 }
1147 }
1148
1149 private void writeBuffer(RegionEntryBuffer buffer) throws IOException {
1150 outputSink.append(buffer);
1151 }
1152
1153 void finish() {
1154 synchronized (controller.dataAvailable) {
1155 shouldStop = true;
1156 controller.dataAvailable.notifyAll();
1157 }
1158 }
1159 }
1160
1161
1162
1163
1164
1165 public static abstract class OutputSink {
1166
1167 protected PipelineController controller;
1168 protected EntryBuffers entryBuffers;
1169
1170 protected ConcurrentHashMap<String, SinkWriter> writers = new ConcurrentHashMap<>();
1171 protected ConcurrentHashMap<String, Long> regionMaximumEditLogSeqNum =
1172 new ConcurrentHashMap<>();
1173
1174 protected final List<WriterThread> writerThreads = Lists.newArrayList();
1175
1176
1177 protected final Set<byte[]> blacklistedRegions = Collections
1178 .synchronizedSet(new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR));
1179
1180 protected boolean closeAndCleanCompleted = false;
1181
1182 protected boolean writersClosed = false;
1183
1184 protected final int numThreads;
1185
1186 protected CancelableProgressable reporter = null;
1187
1188 protected AtomicLong skippedEdits = new AtomicLong();
1189
1190 protected List<Path> splits = null;
1191
1192 public OutputSink(PipelineController controller, EntryBuffers entryBuffers, int numWriters) {
1193 numThreads = numWriters;
1194 this.controller = controller;
1195 this.entryBuffers = entryBuffers;
1196 }
1197
1198 void setReporter(CancelableProgressable reporter) {
1199 this.reporter = reporter;
1200 }
1201
1202
1203
1204
1205 public synchronized void startWriterThreads() {
1206 for (int i = 0; i < numThreads; i++) {
1207 WriterThread t = new WriterThread(controller, entryBuffers, this, i);
1208 t.start();
1209 writerThreads.add(t);
1210 }
1211 }
1212
1213
1214
1215
1216
1217 void updateRegionMaximumEditLogSeqNum(Entry entry) {
1218
1219 synchronized (regionMaximumEditLogSeqNum) {
1220 String encodedRegionName = Bytes.toString(entry.getKey().getEncodedRegionName());
1221 Long currentMaxSeqNum = regionMaximumEditLogSeqNum.get(encodedRegionName);
1222 if (currentMaxSeqNum == null || entry.getKey().getLogSeqNum() > currentMaxSeqNum) {
1223 regionMaximumEditLogSeqNum.put(encodedRegionName, entry.getKey()
1224 .getLogSeqNum());
1225 }
1226 }
1227 }
1228
1229 Long getRegionMaximumEditLogSeqNum(byte[] region) {
1230 return regionMaximumEditLogSeqNum.get(Bytes.toString(region));
1231 }
1232
1233
1234
1235
1236 int getNumOpenWriters() {
1237 return this.writers.size();
1238 }
1239
1240 long getSkippedEdits() {
1241 return this.skippedEdits.get();
1242 }
1243
1244
1245
1246
1247
1248
1249 protected boolean finishWriting(boolean interrupt) throws IOException {
1250 LOG.debug("Waiting for split writer threads to finish");
1251 boolean progress_failed = false;
1252 for (WriterThread t : writerThreads) {
1253 t.finish();
1254 }
1255 if (interrupt) {
1256 for (WriterThread t : writerThreads) {
1257 t.interrupt();
1258 }
1259 }
1260
1261 for (WriterThread t : writerThreads) {
1262 if (!progress_failed && reporter != null && !reporter.progress()) {
1263 progress_failed = true;
1264 }
1265 try {
1266 t.join();
1267 } catch (InterruptedException ie) {
1268 IOException iie = new InterruptedIOException();
1269 iie.initCause(ie);
1270 throw iie;
1271 }
1272 }
1273 controller.checkForErrors();
1274 LOG.info(this.writerThreads.size() + " split writers finished; closing...");
1275 return (!progress_failed);
1276 }
1277
1278 public abstract List<Path> finishWritingAndClose() throws IOException;
1279
1280
1281
1282
1283 public abstract Map<byte[], Long> getOutputCounts();
1284
1285
1286
1287
1288 public abstract int getNumberOfRecoveredRegions();
1289
1290
1291
1292
1293
1294 public abstract void append(RegionEntryBuffer buffer) throws IOException;
1295
1296
1297
1298
1299
1300 public boolean flush() throws IOException {
1301 return false;
1302 }
1303
1304
1305
1306
1307
1308
1309
1310 public abstract boolean keepRegionEvent(Entry entry);
1311 }
1312
1313
1314
1315
1316 class LogRecoveredEditsOutputSink extends OutputSink {
1317
1318 public LogRecoveredEditsOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1319 int numWriters) {
1320
1321
1322
1323
1324
1325 super(controller, entryBuffers, numWriters);
1326 }
1327
1328
1329
1330
1331
1332 @Override
1333 public List<Path> finishWritingAndClose() throws IOException {
1334 boolean isSuccessful = false;
1335 List<Path> result = null;
1336 try {
1337 isSuccessful = finishWriting(false);
1338 } finally {
1339 result = close();
1340 List<IOException> thrown = closeLogWriters(null);
1341 if (thrown != null && !thrown.isEmpty()) {
1342 throw MultipleIOException.createIOException(thrown);
1343 }
1344 }
1345 if (isSuccessful) {
1346 splits = result;
1347 }
1348 return splits;
1349 }
1350
1351
1352 void deleteOneWithFewerEntries(WriterAndPath wap, Path dst)
1353 throws IOException {
1354 long dstMinLogSeqNum = -1L;
1355 try (WAL.Reader reader = walFactory.createReader(walFS, dst)) {
1356 WAL.Entry entry = reader.next();
1357 if (entry != null) {
1358 dstMinLogSeqNum = entry.getKey().getLogSeqNum();
1359 }
1360 } catch (EOFException e) {
1361 if (LOG.isDebugEnabled()) {
1362 LOG.debug(
1363 "Got EOF when reading first WAL entry from " + dst + ", an empty or broken WAL file?",
1364 e);
1365 }
1366 }
1367 if (wap.minLogSeqNum < dstMinLogSeqNum) {
1368 LOG.warn("Found existing old edits file. It could be the result of a previous failed"
1369 + " split attempt or we have duplicated wal entries. Deleting " + dst + ", length="
1370 + walFS.getFileStatus(dst).getLen());
1371 if (!walFS.delete(dst, false)) {
1372 LOG.warn("Failed deleting of old " + dst);
1373 throw new IOException("Failed deleting of old " + dst);
1374 }
1375 } else {
1376 LOG.warn("Found existing old edits file and we have less entries. Deleting " + wap.p
1377 + ", length=" + walFS.getFileStatus(wap.p).getLen());
1378 if (!walFS.delete(wap.p, false)) {
1379 LOG.warn("Failed deleting of " + wap.p);
1380 throw new IOException("Failed deleting of " + wap.p);
1381 }
1382 }
1383 }
1384
1385
1386
1387
1388
1389 List<Path> close() throws IOException {
1390 Preconditions.checkState(!closeAndCleanCompleted);
1391
1392 final List<Path> paths = new ArrayList<Path>();
1393 final List<IOException> thrown = Lists.newArrayList();
1394 ThreadPoolExecutor closeThreadPool = Threads.getBoundedCachedThreadPool(numThreads, 30L,
1395 TimeUnit.SECONDS, new ThreadFactory() {
1396 private int count = 1;
1397
1398 @Override
1399 public Thread newThread(Runnable r) {
1400 Thread t = new Thread(r, "split-log-closeStream-" + count++);
1401 return t;
1402 }
1403 });
1404 CompletionService<Void> completionService =
1405 new ExecutorCompletionService<Void>(closeThreadPool);
1406 boolean progress_failed;
1407 try{
1408 progress_failed = executeCloseTask(completionService, thrown, paths);
1409 } catch (InterruptedException e) {
1410 IOException iie = new InterruptedIOException();
1411 iie.initCause(e);
1412 throw iie;
1413 } catch (ExecutionException e) {
1414 throw new IOException(e.getCause());
1415 } finally {
1416 closeThreadPool.shutdownNow();
1417 }
1418
1419 if (!thrown.isEmpty()) {
1420 throw MultipleIOException.createIOException(thrown);
1421 }
1422 writersClosed = true;
1423 closeAndCleanCompleted = true;
1424 if (progress_failed) {
1425 return null;
1426 }
1427 return paths;
1428 }
1429
1430 boolean executeCloseTask(CompletionService<Void> completionService,
1431 final List<IOException> thrown, final List<Path> paths)
1432 throws InterruptedException, ExecutionException {
1433 for (final Map.Entry<String, SinkWriter> writersEntry : writers.entrySet()) {
1434 if (LOG.isTraceEnabled()) {
1435 LOG.trace("Submitting close of " + ((WriterAndPath) writersEntry.getValue()).p);
1436 }
1437 completionService.submit(new Callable<Void>() {
1438 @Override public Void call() throws Exception {
1439 WriterAndPath wap = (WriterAndPath) writersEntry.getValue();
1440 Path dst = closeWriter(writersEntry.getKey(), wap, thrown);
1441 paths.add(dst);
1442 return null;
1443 }
1444 });
1445 }
1446 boolean progress_failed = false;
1447 for (int i = 0, n = this.writers.size(); i < n; i++) {
1448 Future<Void> future = completionService.take();
1449 future.get();
1450 if (!progress_failed && reporter != null && !reporter.progress()) {
1451 progress_failed = true;
1452 }
1453 }
1454 return progress_failed;
1455 }
1456
1457 Path closeWriter(String encodedRegionName, WriterAndPath wap, List<IOException> thrown)
1458 throws IOException {
1459 if (LOG.isTraceEnabled()) {
1460 LOG.trace("Closing " + wap.p);
1461 }
1462
1463 try {
1464 wap.w.close();
1465 } catch (IOException ioe) {
1466 LOG.error("Couldn't close log at " + wap.p, ioe);
1467 thrown.add(ioe);
1468 return null;
1469 }
1470 if (LOG.isDebugEnabled()) {
1471 LOG.debug("Closed wap " + wap.p + " (wrote " + wap.editsWritten
1472 + " edits, skipped " + wap.editsSkipped + " edits in "
1473 + (wap.nanosSpent / 1000 / 1000) + "ms");
1474 }
1475 if (wap.editsWritten == 0) {
1476
1477 if (walFS.exists(wap.p) && !walFS.delete(wap.p, false)) {
1478 LOG.warn("Failed deleting empty " + wap.p);
1479 throw new IOException("Failed deleting empty " + wap.p);
1480 }
1481 return null;
1482 }
1483
1484 Path dst = getCompletedRecoveredEditsFilePath(wap.p,
1485 regionMaximumEditLogSeqNum.get(encodedRegionName));
1486 try {
1487 if (!dst.equals(wap.p) && walFS.exists(dst)) {
1488 deleteOneWithFewerEntries(wap, dst);
1489 }
1490
1491
1492
1493 if (walFS.exists(wap.p)) {
1494 if (!walFS.rename(wap.p, dst)) {
1495 throw new IOException("Failed renaming " + wap.p + " to " + dst);
1496 }
1497 LOG.info("Rename " + wap.p + " to " + dst);
1498 }
1499 } catch (IOException ioe) {
1500 LOG.error("Couldn't rename " + wap.p + " to " + dst, ioe);
1501 thrown.add(ioe);
1502 return null;
1503 }
1504 return dst;
1505 }
1506
1507
1508 private List<IOException> closeLogWriters(List<IOException> thrown) throws IOException {
1509 if (writersClosed) {
1510 return thrown;
1511 }
1512
1513 if (thrown == null) {
1514 thrown = Lists.newArrayList();
1515 }
1516 try {
1517 for (WriterThread t : writerThreads) {
1518 while (t.isAlive()) {
1519 t.shouldStop = true;
1520 t.interrupt();
1521 try {
1522 t.join(10);
1523 } catch (InterruptedException e) {
1524 IOException iie = new InterruptedIOException();
1525 iie.initCause(e);
1526 throw iie;
1527 }
1528 }
1529 }
1530 } finally {
1531 WriterAndPath wap = null;
1532 for (SinkWriter tmpWAP : writers.values()) {
1533 try {
1534 wap = (WriterAndPath) tmpWAP;
1535 wap.w.close();
1536 } catch (IOException ioe) {
1537 LOG.error("Couldn't close log at " + wap.p, ioe);
1538 thrown.add(ioe);
1539 continue;
1540 }
1541 LOG.info(
1542 "Closed log " + wap.p + " (wrote " + wap.editsWritten + " edits in " + (wap.nanosSpent
1543 / 1000 / 1000) + "ms)");
1544 }
1545 writersClosed = true;
1546 }
1547
1548 return thrown;
1549 }
1550
1551
1552
1553
1554
1555
1556 WriterAndPath getWriterAndPath(Entry entry, boolean reusable) throws IOException {
1557 byte region[] = entry.getKey().getEncodedRegionName();
1558 String regionName = Bytes.toString(region);
1559 WriterAndPath ret = (WriterAndPath) writers.get(regionName);
1560 if (ret != null) {
1561 return ret;
1562 }
1563
1564
1565 if (blacklistedRegions.contains(region)) {
1566 return null;
1567 }
1568 ret = createWAP(region, entry);
1569 if (ret == null) {
1570 blacklistedRegions.add(region);
1571 return null;
1572 }
1573
1574 if(reusable) {
1575 writers.put(regionName, ret);
1576 }
1577 return ret;
1578 }
1579
1580
1581
1582
1583 WriterAndPath createWAP(byte[] region, Entry entry) throws IOException {
1584 String tmpDirName = conf.get(HConstants.TEMPORARY_FS_DIRECTORY_KEY,
1585 HConstants.DEFAULT_TEMPORARY_HDFS_DIRECTORY);
1586 Path regionedits = getRegionSplitEditsPath(entry,
1587 fileBeingSplit.getPath().getName(), tmpDirName, conf);
1588 if (regionedits == null) {
1589 return null;
1590 }
1591 if (walFS.exists(regionedits)) {
1592 LOG.warn("Found old edits file. It could be the "
1593 + "result of a previous failed split attempt. Deleting " + regionedits + ", length="
1594 + walFS.getFileStatus(regionedits).getLen());
1595 if (!walFS.delete(regionedits, false)) {
1596 LOG.warn("Failed delete of old " + regionedits);
1597 }
1598 }
1599 Writer w = createWriter(regionedits);
1600 LOG.debug("Creating writer path=" + regionedits);
1601 return new WriterAndPath(regionedits, w, entry.getKey().getLogSeqNum());
1602 }
1603
1604 void filterCellByStore(Entry logEntry) {
1605 Map<byte[], Long> maxSeqIdInStores =
1606 regionMaxSeqIdInStores.get(Bytes.toString(logEntry.getKey().getEncodedRegionName()));
1607 if (maxSeqIdInStores == null || maxSeqIdInStores.isEmpty()) {
1608 return;
1609 }
1610
1611
1612 ArrayList<Cell> keptCells = new ArrayList<Cell>(logEntry.getEdit().getCells().size());
1613 for (Cell cell : logEntry.getEdit().getCells()) {
1614 if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1615 keptCells.add(cell);
1616 } else {
1617 byte[] family = CellUtil.cloneFamily(cell);
1618 Long maxSeqId = maxSeqIdInStores.get(family);
1619
1620
1621 if (maxSeqId == null || maxSeqId.longValue() < logEntry.getKey().getLogSeqNum()) {
1622 keptCells.add(cell);
1623 }
1624 }
1625 }
1626
1627
1628
1629
1630 logEntry.getEdit().setCells(keptCells);
1631 }
1632
1633 @Override
1634 public void append(RegionEntryBuffer buffer) throws IOException {
1635 appendBuffer(buffer, true);
1636 }
1637
1638
1639 WriterAndPath appendBuffer(RegionEntryBuffer buffer, boolean reusable) throws IOException{
1640 List<Entry> entries = buffer.entryBuffer;
1641 if (entries.isEmpty()) {
1642 LOG.warn("got an empty buffer, skipping");
1643 return null;
1644 }
1645 WriterAndPath wap = null;
1646
1647 long startTime = System.nanoTime();
1648 try {
1649 int editsCount = 0;
1650
1651 for (Entry logEntry : entries) {
1652 if (wap == null) {
1653 wap = getWriterAndPath(logEntry, reusable);
1654 if (wap == null) {
1655 if (LOG.isDebugEnabled()) {
1656 LOG.debug("getWriterAndPath decided we don't need to write edits for " + logEntry);
1657 }
1658 return null;
1659 }
1660 }
1661 filterCellByStore(logEntry);
1662 if (!logEntry.getEdit().isEmpty()) {
1663 wap.w.append(logEntry);
1664 this.updateRegionMaximumEditLogSeqNum(logEntry);
1665 editsCount++;
1666 } else {
1667 wap.incrementSkippedEdits(1);
1668 }
1669 }
1670
1671 wap.incrementEdits(editsCount);
1672 wap.incrementNanoTime(System.nanoTime() - startTime);
1673 } catch (IOException e) {
1674 e = RemoteExceptionHandler.checkIOException(e);
1675 LOG.fatal(" Got while writing log entry to log", e);
1676 throw e;
1677 }
1678 return wap;
1679 }
1680
1681 @Override
1682 public boolean keepRegionEvent(Entry entry) {
1683 ArrayList<Cell> cells = entry.getEdit().getCells();
1684 for (int i = 0; i < cells.size(); i++) {
1685 if (WALEdit.isCompactionMarker(cells.get(i))) {
1686 return true;
1687 }
1688 }
1689 return false;
1690 }
1691
1692
1693
1694
1695 @Override
1696 public Map<byte[], Long> getOutputCounts() {
1697 TreeMap<byte[], Long> ret = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
1698 synchronized (writers) {
1699 for (Map.Entry<String, SinkWriter> entry : writers.entrySet()) {
1700 ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
1701 }
1702 }
1703 return ret;
1704 }
1705
1706 @Override
1707 public int getNumberOfRecoveredRegions() {
1708 return writers.size();
1709 }
1710 }
1711
1712
1713
1714
1715 class BoundedLogWriterCreationOutputSink extends LogRecoveredEditsOutputSink{
1716
1717 ConcurrentHashMap<String, Long> regionRecoverStatMap = new ConcurrentHashMap<>();
1718
1719
1720 public BoundedLogWriterCreationOutputSink(PipelineController controller,
1721 EntryBuffers entryBuffers, int numWriters){
1722 super(controller, entryBuffers, numWriters);
1723 }
1724
1725 @Override
1726 public List<Path> finishWritingAndClose() throws IOException {
1727 boolean isSuccessful;
1728 List<Path> result;
1729 try {
1730 isSuccessful = finishWriting(false);
1731 } finally {
1732 result = close();
1733 }
1734 if (isSuccessful) {
1735 splits = result;
1736 }
1737 return splits;
1738 }
1739
1740 @Override
1741 boolean executeCloseTask(CompletionService<Void> closeCompletionService,
1742 final List<IOException> thrown, final List<Path> paths)
1743 throws InterruptedException, ExecutionException {
1744 for (final Map.Entry<byte[], RegionEntryBuffer> buffer : entryBuffers.buffers.entrySet()) {
1745 LOG.info("Submitting write then close of " +
1746 Bytes.toString(buffer.getValue().encodedRegionName));
1747 closeCompletionService.submit(new Callable<Void>() {
1748 public Void call() throws Exception {
1749 Path dst = writeThenClose(buffer.getValue());
1750 paths.add(dst);
1751 return null;
1752 }
1753 });
1754 }
1755
1756 boolean progress_failed = false;
1757 for (int i = 0, n = entryBuffers.buffers.size(); i < n; i++) {
1758 Future<Void> future = closeCompletionService.take();
1759 future.get();
1760 if (!progress_failed && reporter != null && !reporter.progress()) {
1761 progress_failed = true;
1762 }
1763 }
1764 return progress_failed;
1765 }
1766
1767 @Override
1768 public Map<byte[], Long> getOutputCounts() {
1769 Map<byte[], Long> regionRecoverStatMapResult = new HashMap<>();
1770 for(Map.Entry<String, Long> entry: regionRecoverStatMap.entrySet()){
1771 regionRecoverStatMapResult.put(Bytes.toBytes(entry.getKey()), entry.getValue());
1772 }
1773 return regionRecoverStatMapResult;
1774 }
1775
1776 @Override
1777 public int getNumberOfRecoveredRegions() {
1778 return regionRecoverStatMap.size();
1779 }
1780
1781 @Override
1782 public void append(RegionEntryBuffer buffer) throws IOException {
1783 writeThenClose(buffer);
1784 }
1785
1786 private Path writeThenClose(RegionEntryBuffer buffer) throws IOException {
1787 WriterAndPath wap = appendBuffer(buffer, false);
1788 Path dst = null;
1789 if(wap != null){
1790 String encodedRegionName = Bytes.toString(buffer.encodedRegionName);
1791 Long value = regionRecoverStatMap.putIfAbsent(encodedRegionName, wap.editsWritten);
1792 if(value != null){
1793 Long newValue = regionRecoverStatMap.get(encodedRegionName) + wap.editsWritten;
1794 regionRecoverStatMap.put(encodedRegionName, newValue);
1795 }
1796 }
1797
1798 List<IOException> thrown = new ArrayList<>();
1799 if(wap != null) {
1800 dst = closeWriter(Bytes.toString(buffer.encodedRegionName), wap, thrown);
1801 }
1802
1803 if(!thrown.isEmpty()){
1804 throw MultipleIOException.createIOException(thrown);
1805 }
1806 return dst;
1807 }
1808 }
1809
1810
1811
1812
1813
1814 public abstract static class SinkWriter {
1815
1816 long editsWritten = 0;
1817
1818 long editsSkipped = 0;
1819
1820 long nanosSpent = 0;
1821
1822 void incrementEdits(int edits) {
1823 editsWritten += edits;
1824 }
1825
1826 void incrementSkippedEdits(int skipped) {
1827 editsSkipped += skipped;
1828 }
1829
1830 void incrementNanoTime(long nanos) {
1831 nanosSpent += nanos;
1832 }
1833 }
1834
1835
1836
1837
1838
1839 private final static class WriterAndPath extends SinkWriter {
1840 final Path p;
1841 final Writer w;
1842 final long minLogSeqNum;
1843
1844 WriterAndPath(final Path p, final Writer w, final long minLogSeqNum) {
1845 this.p = p;
1846 this.w = w;
1847 this.minLogSeqNum = minLogSeqNum;
1848 }
1849 }
1850
1851
1852
1853
1854 class LogReplayOutputSink extends OutputSink {
1855 private static final double BUFFER_THRESHOLD = 0.35;
1856 private static final String KEY_DELIMITER = "#";
1857
1858 private long waitRegionOnlineTimeOut;
1859 private final Set<String> recoveredRegions = Collections.synchronizedSet(new HashSet<String>());
1860 private final Map<String, RegionServerWriter> rsWriters =
1861 new ConcurrentHashMap<String, RegionServerWriter>();
1862
1863 private final Map<String, HRegionLocation> onlineRegions =
1864 new ConcurrentHashMap<String, HRegionLocation>();
1865
1866 private final Map<TableName, HConnection> tableNameToHConnectionMap = Collections
1867 .synchronizedMap(new TreeMap<TableName, HConnection>());
1868
1869
1870
1871
1872 private final Map<String, List<Pair<HRegionLocation, Entry>>> serverToBufferQueueMap =
1873 new ConcurrentHashMap<String, List<Pair<HRegionLocation, Entry>>>();
1874 private final List<Throwable> thrown = new ArrayList<Throwable>();
1875
1876
1877
1878
1879
1880 private LogRecoveredEditsOutputSink logRecoveredEditsOutputSink;
1881 private boolean hasEditsInDisablingOrDisabledTables = false;
1882
1883 public LogReplayOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1884 int numWriters) {
1885 super(controller, entryBuffers, numWriters);
1886 this.waitRegionOnlineTimeOut = conf.getInt(HConstants.HBASE_SPLITLOG_MANAGER_TIMEOUT,
1887 ZKSplitLogManagerCoordination.DEFAULT_TIMEOUT);
1888 this.logRecoveredEditsOutputSink = new LogRecoveredEditsOutputSink(controller,
1889 entryBuffers, numWriters);
1890 this.logRecoveredEditsOutputSink.setReporter(reporter);
1891 }
1892
1893 @Override
1894 public void append(RegionEntryBuffer buffer) throws IOException {
1895 List<Entry> entries = buffer.entryBuffer;
1896 if (entries.isEmpty()) {
1897 LOG.warn("got an empty buffer, skipping");
1898 return;
1899 }
1900
1901
1902 if (disablingOrDisabledTables.contains(buffer.tableName)) {
1903
1904 logRecoveredEditsOutputSink.append(buffer);
1905 hasEditsInDisablingOrDisabledTables = true;
1906
1907 addToRecoveredRegions(Bytes.toString(buffer.encodedRegionName));
1908 return;
1909 }
1910
1911
1912 groupEditsByServer(entries);
1913
1914
1915 String maxLocKey = null;
1916 int maxSize = 0;
1917 List<Pair<HRegionLocation, Entry>> maxQueue = null;
1918 synchronized (this.serverToBufferQueueMap) {
1919 for (Map.Entry<String, List<Pair<HRegionLocation, Entry>>> entry:
1920 serverToBufferQueueMap.entrySet()) {
1921 List<Pair<HRegionLocation, Entry>> curQueue = entry.getValue();
1922 if (curQueue.size() > maxSize) {
1923 maxSize = curQueue.size();
1924 maxQueue = curQueue;
1925 maxLocKey = entry.getKey();
1926 }
1927 }
1928 if (maxSize < minBatchSize
1929 && entryBuffers.totalBuffered < BUFFER_THRESHOLD * entryBuffers.maxHeapUsage) {
1930
1931 return;
1932 } else if (maxSize > 0) {
1933 this.serverToBufferQueueMap.remove(maxLocKey);
1934 }
1935 }
1936
1937 if (maxSize > 0) {
1938 processWorkItems(maxLocKey, maxQueue);
1939 }
1940 }
1941
1942 private void addToRecoveredRegions(String encodedRegionName) {
1943 if (!recoveredRegions.contains(encodedRegionName)) {
1944 recoveredRegions.add(encodedRegionName);
1945 }
1946 }
1947
1948
1949
1950
1951
1952 private void groupEditsByServer(List<Entry> entries) throws IOException {
1953 Set<TableName> nonExistentTables = null;
1954 Long cachedLastFlushedSequenceId = -1l;
1955 for (Entry entry : entries) {
1956 WALEdit edit = entry.getEdit();
1957 TableName table = entry.getKey().getTablename();
1958
1959 entry.getKey().setScopes(null);
1960 String encodeRegionNameStr = Bytes.toString(entry.getKey().getEncodedRegionName());
1961
1962 if (nonExistentTables != null && nonExistentTables.contains(table)) {
1963 this.skippedEdits.incrementAndGet();
1964 continue;
1965 }
1966
1967 Map<byte[], Long> maxStoreSequenceIds = null;
1968 boolean needSkip = false;
1969 HRegionLocation loc = null;
1970 String locKey = null;
1971 List<Cell> cells = edit.getCells();
1972 List<Cell> skippedCells = new ArrayList<Cell>();
1973 HConnection hconn = this.getConnectionByTableName(table);
1974
1975 for (Cell cell : cells) {
1976 byte[] row = CellUtil.cloneRow(cell);
1977 byte[] family = CellUtil.cloneFamily(cell);
1978 boolean isCompactionEntry = false;
1979 if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1980 CompactionDescriptor compaction = WALEdit.getCompaction(cell);
1981 if (compaction != null && compaction.hasRegionName()) {
1982 try {
1983 byte[][] regionName = HRegionInfo.parseRegionName(compaction.getRegionName()
1984 .toByteArray());
1985 row = regionName[1];
1986 family = compaction.getFamilyName().toByteArray();
1987 isCompactionEntry = true;
1988 } catch (Exception ex) {
1989 LOG.warn("Unexpected exception received, ignoring " + ex);
1990 skippedCells.add(cell);
1991 continue;
1992 }
1993 } else {
1994 skippedCells.add(cell);
1995 continue;
1996 }
1997 }
1998
1999 try {
2000 loc =
2001 locateRegionAndRefreshLastFlushedSequenceId(hconn, table, row,
2002 encodeRegionNameStr);
2003
2004 if (isCompactionEntry && !encodeRegionNameStr.equalsIgnoreCase(
2005 loc.getRegionInfo().getEncodedName())) {
2006 LOG.info("Not replaying a compaction marker for an older region: "
2007 + encodeRegionNameStr);
2008 needSkip = true;
2009 }
2010 } catch (TableNotFoundException ex) {
2011
2012 LOG.info("Table " + table + " doesn't exist. Skip log replay for region "
2013 + encodeRegionNameStr);
2014 lastFlushedSequenceIds.put(encodeRegionNameStr, Long.MAX_VALUE);
2015 if (nonExistentTables == null) {
2016 nonExistentTables = new TreeSet<TableName>();
2017 }
2018 nonExistentTables.add(table);
2019 this.skippedEdits.incrementAndGet();
2020 needSkip = true;
2021 break;
2022 }
2023
2024 cachedLastFlushedSequenceId =
2025 lastFlushedSequenceIds.get(loc.getRegionInfo().getEncodedName());
2026 if (cachedLastFlushedSequenceId != null
2027 && cachedLastFlushedSequenceId >= entry.getKey().getLogSeqNum()) {
2028
2029 this.skippedEdits.incrementAndGet();
2030 needSkip = true;
2031 break;
2032 } else {
2033 if (maxStoreSequenceIds == null) {
2034 maxStoreSequenceIds =
2035 regionMaxSeqIdInStores.get(loc.getRegionInfo().getEncodedName());
2036 }
2037 if (maxStoreSequenceIds != null) {
2038 Long maxStoreSeqId = maxStoreSequenceIds.get(family);
2039 if (maxStoreSeqId == null || maxStoreSeqId >= entry.getKey().getLogSeqNum()) {
2040
2041 skippedCells.add(cell);
2042 continue;
2043 }
2044 }
2045 }
2046 }
2047
2048
2049 if (loc == null || needSkip) continue;
2050
2051 if (!skippedCells.isEmpty()) {
2052 cells.removeAll(skippedCells);
2053 }
2054
2055 synchronized (serverToBufferQueueMap) {
2056 locKey = loc.getHostnamePort() + KEY_DELIMITER + table;
2057 List<Pair<HRegionLocation, Entry>> queue = serverToBufferQueueMap.get(locKey);
2058 if (queue == null) {
2059 queue =
2060 Collections.synchronizedList(new ArrayList<Pair<HRegionLocation, Entry>>());
2061 serverToBufferQueueMap.put(locKey, queue);
2062 }
2063 queue.add(new Pair<HRegionLocation, Entry>(loc, entry));
2064 }
2065
2066 addToRecoveredRegions(loc.getRegionInfo().getEncodedName());
2067 }
2068 }
2069
2070
2071
2072
2073
2074
2075 private HRegionLocation locateRegionAndRefreshLastFlushedSequenceId(HConnection hconn,
2076 TableName table, byte[] row, String originalEncodedRegionName) throws IOException {
2077
2078 HRegionLocation loc = onlineRegions.get(originalEncodedRegionName);
2079 if(loc != null) return loc;
2080
2081 loc = hconn.getRegionLocation(table, row, true);
2082 if (loc == null) {
2083 throw new IOException("Can't locate location for row:" + Bytes.toString(row)
2084 + " of table:" + table);
2085 }
2086
2087 if (!originalEncodedRegionName.equalsIgnoreCase(loc.getRegionInfo().getEncodedName())) {
2088
2089 lastFlushedSequenceIds.put(originalEncodedRegionName, Long.MAX_VALUE);
2090 HRegionLocation tmpLoc = onlineRegions.get(loc.getRegionInfo().getEncodedName());
2091 if (tmpLoc != null) return tmpLoc;
2092 }
2093
2094 Long lastFlushedSequenceId = -1l;
2095 AtomicBoolean isRecovering = new AtomicBoolean(true);
2096 loc = waitUntilRegionOnline(loc, row, this.waitRegionOnlineTimeOut, isRecovering);
2097 if (!isRecovering.get()) {
2098
2099
2100 lastFlushedSequenceIds.put(loc.getRegionInfo().getEncodedName(), Long.MAX_VALUE);
2101 LOG.info("logReplay skip region: " + loc.getRegionInfo().getEncodedName()
2102 + " because it's not in recovering.");
2103 } else {
2104 Long cachedLastFlushedSequenceId =
2105 lastFlushedSequenceIds.get(loc.getRegionInfo().getEncodedName());
2106
2107
2108
2109 RegionStoreSequenceIds ids =
2110 csm.getSplitLogWorkerCoordination().getRegionFlushedSequenceId(failedServerName,
2111 loc.getRegionInfo().getEncodedName());
2112 if (ids != null) {
2113 lastFlushedSequenceId = ids.getLastFlushedSequenceId();
2114 Map<byte[], Long> storeIds = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
2115 List<StoreSequenceId> maxSeqIdInStores = ids.getStoreSequenceIdList();
2116 for (StoreSequenceId id : maxSeqIdInStores) {
2117 storeIds.put(id.getFamilyName().toByteArray(), id.getSequenceId());
2118 }
2119 regionMaxSeqIdInStores.put(loc.getRegionInfo().getEncodedName(), storeIds);
2120 }
2121
2122 if (cachedLastFlushedSequenceId == null
2123 || lastFlushedSequenceId > cachedLastFlushedSequenceId) {
2124 lastFlushedSequenceIds.put(loc.getRegionInfo().getEncodedName(), lastFlushedSequenceId);
2125 }
2126 }
2127
2128 onlineRegions.put(loc.getRegionInfo().getEncodedName(), loc);
2129 return loc;
2130 }
2131
2132 private void processWorkItems(String key, List<Pair<HRegionLocation, Entry>> actions)
2133 throws IOException {
2134 RegionServerWriter rsw = null;
2135
2136 long startTime = System.nanoTime();
2137 try {
2138 rsw = getRegionServerWriter(key);
2139 rsw.sink.replayEntries(actions);
2140
2141
2142 rsw.incrementEdits(actions.size());
2143 rsw.incrementNanoTime(System.nanoTime() - startTime);
2144 } catch (IOException e) {
2145 e = RemoteExceptionHandler.checkIOException(e);
2146 LOG.fatal(" Got while writing log entry to log", e);
2147 throw e;
2148 }
2149 }
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160 private HRegionLocation waitUntilRegionOnline(HRegionLocation loc, byte[] row,
2161 final long timeout, AtomicBoolean isRecovering)
2162 throws IOException {
2163 final long endTime = EnvironmentEdgeManager.currentTime() + timeout;
2164 final long pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
2165 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
2166 boolean reloadLocation = false;
2167 TableName tableName = loc.getRegionInfo().getTable();
2168 int tries = 0;
2169 Throwable cause = null;
2170 while (endTime > EnvironmentEdgeManager.currentTime()) {
2171 try {
2172
2173 HConnection hconn = getConnectionByTableName(tableName);
2174 if(reloadLocation) {
2175 loc = hconn.getRegionLocation(tableName, row, true);
2176 }
2177 BlockingInterface remoteSvr = hconn.getAdmin(loc.getServerName());
2178 HRegionInfo region = loc.getRegionInfo();
2179 try {
2180 GetRegionInfoRequest request =
2181 RequestConverter.buildGetRegionInfoRequest(region.getRegionName());
2182 GetRegionInfoResponse response = remoteSvr.getRegionInfo(null, request);
2183 if (HRegionInfo.convert(response.getRegionInfo()) != null) {
2184 isRecovering.set((response.hasIsRecovering()) ? response.getIsRecovering() : true);
2185 return loc;
2186 }
2187 } catch (ServiceException se) {
2188 throw ProtobufUtil.getRemoteException(se);
2189 }
2190 } catch (IOException e) {
2191 cause = e.getCause();
2192 if(!(cause instanceof RegionOpeningException)) {
2193 reloadLocation = true;
2194 }
2195 }
2196 long expectedSleep = ConnectionUtils.getPauseTime(pause, tries);
2197 try {
2198 Thread.sleep(expectedSleep);
2199 } catch (InterruptedException e) {
2200 throw new IOException("Interrupted when waiting region " +
2201 loc.getRegionInfo().getEncodedName() + " online.", e);
2202 }
2203 tries++;
2204 }
2205
2206 throw new IOException("Timeout when waiting region " + loc.getRegionInfo().getEncodedName() +
2207 " online for " + timeout + " milliseconds.", cause);
2208 }
2209
2210 @Override
2211 public boolean flush() throws IOException {
2212 String curLoc = null;
2213 int curSize = 0;
2214 List<Pair<HRegionLocation, Entry>> curQueue = null;
2215 synchronized (this.serverToBufferQueueMap) {
2216 for (Map.Entry<String, List<Pair<HRegionLocation, Entry>>> entry :
2217 serverToBufferQueueMap.entrySet()) {
2218 String locationKey = entry.getKey();
2219 curQueue = entry.getValue();
2220 if (!curQueue.isEmpty()) {
2221 curSize = curQueue.size();
2222 curLoc = locationKey;
2223 break;
2224 }
2225 }
2226 if (curSize > 0) {
2227 this.serverToBufferQueueMap.remove(curLoc);
2228 }
2229 }
2230
2231 if (curSize > 0) {
2232 this.processWorkItems(curLoc, curQueue);
2233
2234 synchronized(controller.dataAvailable) {
2235 controller.dataAvailable.notifyAll();
2236 }
2237 return true;
2238 }
2239 return false;
2240 }
2241
2242 @Override
2243 public boolean keepRegionEvent(Entry entry) {
2244 return true;
2245 }
2246
2247 void addWriterError(Throwable t) {
2248 thrown.add(t);
2249 }
2250
2251 @Override
2252 public List<Path> finishWritingAndClose() throws IOException {
2253 try {
2254 if (!finishWriting(false)) {
2255 return null;
2256 }
2257 if (hasEditsInDisablingOrDisabledTables) {
2258 splits = logRecoveredEditsOutputSink.finishWritingAndClose();
2259 } else {
2260 splits = new ArrayList<Path>();
2261 }
2262
2263 return splits;
2264 } finally {
2265 List<IOException> thrown = closeRegionServerWriters();
2266 if (thrown != null && !thrown.isEmpty()) {
2267 throw MultipleIOException.createIOException(thrown);
2268 }
2269 }
2270 }
2271
2272 @Override
2273 int getNumOpenWriters() {
2274 return this.rsWriters.size() + this.logRecoveredEditsOutputSink.getNumOpenWriters();
2275 }
2276
2277 private List<IOException> closeRegionServerWriters() throws IOException {
2278 List<IOException> result = null;
2279 if (!writersClosed) {
2280 result = Lists.newArrayList();
2281 try {
2282 for (WriterThread t : writerThreads) {
2283 while (t.isAlive()) {
2284 t.shouldStop = true;
2285 t.interrupt();
2286 try {
2287 t.join(10);
2288 } catch (InterruptedException e) {
2289 IOException iie = new InterruptedIOException();
2290 iie.initCause(e);
2291 throw iie;
2292 }
2293 }
2294 }
2295 } finally {
2296 synchronized (rsWriters) {
2297 for (Map.Entry<String, RegionServerWriter> entry : rsWriters.entrySet()) {
2298 String locationKey = entry.getKey();
2299 RegionServerWriter tmpW = entry.getValue();
2300 try {
2301 tmpW.close();
2302 } catch (IOException ioe) {
2303 LOG.error("Couldn't close writer for region server:" + locationKey, ioe);
2304 result.add(ioe);
2305 }
2306 }
2307 }
2308
2309
2310 synchronized (this.tableNameToHConnectionMap) {
2311 for (Map.Entry<TableName, HConnection> entry :
2312 tableNameToHConnectionMap.entrySet()) {
2313 TableName tableName = entry.getKey();
2314 HConnection hconn = entry.getValue();
2315 try {
2316 hconn.clearRegionCache();
2317 hconn.close();
2318 } catch (IOException ioe) {
2319 result.add(ioe);
2320 }
2321 }
2322 }
2323 writersClosed = true;
2324 }
2325 }
2326 return result;
2327 }
2328
2329 @Override
2330 public Map<byte[], Long> getOutputCounts() {
2331 TreeMap<byte[], Long> ret = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
2332 synchronized (rsWriters) {
2333 for (Map.Entry<String, RegionServerWriter> entry : rsWriters.entrySet()) {
2334 ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
2335 }
2336 }
2337 return ret;
2338 }
2339
2340 @Override
2341 public int getNumberOfRecoveredRegions() {
2342 return this.recoveredRegions.size();
2343 }
2344
2345
2346
2347
2348
2349
2350 private RegionServerWriter getRegionServerWriter(String loc) throws IOException {
2351 RegionServerWriter ret = rsWriters.get(loc);
2352 if (ret != null) {
2353 return ret;
2354 }
2355
2356 TableName tableName = getTableFromLocationStr(loc);
2357 if(tableName == null){
2358 throw new IOException("Invalid location string:" + loc + " found. Replay aborted.");
2359 }
2360
2361 HConnection hconn = getConnectionByTableName(tableName);
2362 synchronized (rsWriters) {
2363 ret = rsWriters.get(loc);
2364 if (ret == null) {
2365 ret = new RegionServerWriter(conf, tableName, hconn);
2366 rsWriters.put(loc, ret);
2367 }
2368 }
2369 return ret;
2370 }
2371
2372 private HConnection getConnectionByTableName(final TableName tableName) throws IOException {
2373 HConnection hconn = this.tableNameToHConnectionMap.get(tableName);
2374 if (hconn == null) {
2375 synchronized (this.tableNameToHConnectionMap) {
2376 hconn = this.tableNameToHConnectionMap.get(tableName);
2377 if (hconn == null) {
2378 hconn = HConnectionManager.getConnection(conf);
2379 this.tableNameToHConnectionMap.put(tableName, hconn);
2380 }
2381 }
2382 }
2383 return hconn;
2384 }
2385 private TableName getTableFromLocationStr(String loc) {
2386
2387
2388
2389 String[] splits = loc.split(KEY_DELIMITER);
2390 if (splits.length != 2) {
2391 return null;
2392 }
2393 return TableName.valueOf(splits[1]);
2394 }
2395 }
2396
2397
2398
2399
2400
2401 private final static class RegionServerWriter extends SinkWriter {
2402 final WALEditsReplaySink sink;
2403
2404 RegionServerWriter(final Configuration conf, final TableName tableName, final HConnection conn)
2405 throws IOException {
2406 this.sink = new WALEditsReplaySink(conf, tableName, conn);
2407 }
2408
2409 void close() throws IOException {
2410 }
2411 }
2412
2413 static class CorruptedLogFileException extends Exception {
2414 private static final long serialVersionUID = 1L;
2415
2416 CorruptedLogFileException(String s) {
2417 super(s);
2418 }
2419 }
2420
2421
2422 public static class MutationReplay implements Comparable<MutationReplay> {
2423 public MutationReplay(MutationType type, Mutation mutation, long nonceGroup, long nonce) {
2424 this.type = type;
2425 this.mutation = mutation;
2426 if(this.mutation.getDurability() != Durability.SKIP_WAL) {
2427
2428 this.mutation.setDurability(Durability.ASYNC_WAL);
2429 }
2430 this.nonceGroup = nonceGroup;
2431 this.nonce = nonce;
2432 }
2433
2434 public final MutationType type;
2435 public final Mutation mutation;
2436 public final long nonceGroup;
2437 public final long nonce;
2438
2439 @Override
2440 public int compareTo(final MutationReplay d) {
2441 return this.mutation.compareTo(d.mutation);
2442 }
2443
2444 @Override
2445 public boolean equals(Object obj) {
2446 if(!(obj instanceof MutationReplay)) {
2447 return false;
2448 } else {
2449 return this.compareTo((MutationReplay)obj) == 0;
2450 }
2451 }
2452
2453 @Override
2454 public int hashCode() {
2455 return this.mutation.hashCode();
2456 }
2457 }
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470 public static List<MutationReplay> getMutationsFromWALEntry(WALEntry entry, CellScanner cells,
2471 Pair<WALKey, WALEdit> logEntry, Durability durability)
2472 throws IOException {
2473 if (entry == null) {
2474
2475 return new ArrayList<MutationReplay>();
2476 }
2477
2478 long replaySeqId = (entry.getKey().hasOrigSequenceNumber()) ?
2479 entry.getKey().getOrigSequenceNumber() : entry.getKey().getLogSequenceNumber();
2480 int count = entry.getAssociatedCellCount();
2481 List<MutationReplay> mutations = new ArrayList<MutationReplay>();
2482 Cell previousCell = null;
2483 Mutation m = null;
2484 WALKey key = null;
2485 WALEdit val = null;
2486 if (logEntry != null) val = new WALEdit();
2487
2488 for (int i = 0; i < count; i++) {
2489
2490 if (!cells.advance()) {
2491 throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
2492 }
2493 Cell cell = cells.current();
2494 if (val != null) val.add(cell);
2495
2496 boolean isNewRowOrType =
2497 previousCell == null || previousCell.getTypeByte() != cell.getTypeByte()
2498 || !CellUtil.matchingRow(previousCell, cell);
2499 if (isNewRowOrType) {
2500
2501 if (CellUtil.isDelete(cell)) {
2502 m = new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
2503
2504 mutations.add(new MutationReplay(
2505 MutationType.DELETE, m, HConstants.NO_NONCE, HConstants.NO_NONCE));
2506 } else {
2507 m = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
2508
2509 long nonceGroup = entry.getKey().hasNonceGroup()
2510 ? entry.getKey().getNonceGroup() : HConstants.NO_NONCE;
2511 long nonce = entry.getKey().hasNonce() ? entry.getKey().getNonce() : HConstants.NO_NONCE;
2512 mutations.add(new MutationReplay(MutationType.PUT, m, nonceGroup, nonce));
2513 }
2514 }
2515 if (CellUtil.isDelete(cell)) {
2516 ((Delete) m).addDeleteMarker(cell);
2517 } else {
2518 ((Put) m).add(cell);
2519 }
2520 m.setDurability(durability);
2521 previousCell = cell;
2522 }
2523
2524
2525 if (logEntry != null) {
2526 org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey walKeyProto = entry.getKey();
2527 List<UUID> clusterIds = new ArrayList<UUID>(walKeyProto.getClusterIdsCount());
2528 for (HBaseProtos.UUID uuid : entry.getKey().getClusterIdsList()) {
2529 clusterIds.add(new UUID(uuid.getMostSigBits(), uuid.getLeastSigBits()));
2530 }
2531
2532 key = new HLogKey(walKeyProto.getEncodedRegionName().toByteArray(), TableName.valueOf(
2533 walKeyProto.getTableName().toByteArray()), replaySeqId, walKeyProto.getWriteTime(),
2534 clusterIds, walKeyProto.getNonceGroup(), walKeyProto.getNonce(), null);
2535 logEntry.setFirst(key);
2536 logEntry.setSecond(val);
2537 }
2538
2539 return mutations;
2540 }
2541 }