1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.procedure2.store.wal;
20
21 import java.io.IOException;
22 import java.io.FileNotFoundException;
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import java.util.concurrent.atomic.AtomicLong;
25 import java.util.concurrent.locks.Condition;
26 import java.util.concurrent.locks.ReentrantLock;
27 import java.util.concurrent.LinkedTransferQueue;
28 import java.util.concurrent.CopyOnWriteArrayList;
29 import java.util.concurrent.TimeUnit;
30 import java.util.Arrays;
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.LinkedList;
36 import java.util.Set;
37
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40 import org.apache.hadoop.conf.Configuration;
41 import org.apache.hadoop.fs.FSDataOutputStream;
42 import org.apache.hadoop.fs.FileAlreadyExistsException;
43 import org.apache.hadoop.fs.FileStatus;
44 import org.apache.hadoop.fs.FileSystem;
45 import org.apache.hadoop.fs.Path;
46 import org.apache.hadoop.fs.PathFilter;
47 import org.apache.hadoop.hbase.classification.InterfaceAudience;
48 import org.apache.hadoop.hbase.classification.InterfaceStability;
49 import org.apache.hadoop.hbase.procedure2.Procedure;
50 import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
51 import org.apache.hadoop.hbase.procedure2.store.ProcedureStoreTracker;
52 import org.apache.hadoop.hbase.procedure2.util.ByteSlot;
53 import org.apache.hadoop.hbase.procedure2.util.StringUtils;
54 import org.apache.hadoop.hbase.protobuf.generated.ProcedureProtos.ProcedureWALHeader;
55
56
57
58
59 @InterfaceAudience.Private
60 @InterfaceStability.Evolving
61 public class WALProcedureStore implements ProcedureStore {
62 private static final Log LOG = LogFactory.getLog(WALProcedureStore.class);
63
64 public interface LeaseRecovery {
65 void recoverFileLease(FileSystem fs, Path path) throws IOException;
66 }
67
68 private static final int MAX_RETRIES_BEFORE_ABORT = 3;
69
70 private static final String SYNC_WAIT_MSEC_CONF_KEY = "hbase.procedure.store.wal.sync.wait.msec";
71 private static final int DEFAULT_SYNC_WAIT_MSEC = 100;
72
73 private static final String USE_HSYNC_CONF_KEY = "hbase.procedure.store.wal.use.hsync";
74 private static final boolean DEFAULT_USE_HSYNC = true;
75
76 private static final String ROLL_THRESHOLD_CONF_KEY = "hbase.procedure.store.wal.roll.threshold";
77 private static final long DEFAULT_ROLL_THRESHOLD = 32 * 1024 * 1024;
78
79 private final CopyOnWriteArrayList<ProcedureStoreListener> listeners =
80 new CopyOnWriteArrayList<ProcedureStoreListener>();
81
82 private final LinkedList<ProcedureWALFile> logs = new LinkedList<ProcedureWALFile>();
83 private final ProcedureStoreTracker storeTracker = new ProcedureStoreTracker();
84 private final AtomicBoolean running = new AtomicBoolean(false);
85 private final ReentrantLock lock = new ReentrantLock();
86 private final Condition waitCond = lock.newCondition();
87 private final Condition slotCond = lock.newCondition();
88 private final Condition syncCond = lock.newCondition();
89
90 private final LeaseRecovery leaseRecovery;
91 private final Configuration conf;
92 private final FileSystem fs;
93 private final Path logDir;
94
95 private AtomicBoolean inSync = new AtomicBoolean(false);
96 private LinkedTransferQueue<ByteSlot> slotsCache = null;
97 private Set<ProcedureWALFile> corruptedLogs = null;
98 private AtomicLong totalSynced = new AtomicLong(0);
99 private FSDataOutputStream stream = null;
100 private long lastRollTs = 0;
101 private long flushLogId = 0;
102 private int slotIndex = 0;
103 private Thread syncThread;
104 private ByteSlot[] slots;
105
106 private long rollThreshold;
107 private boolean useHsync;
108 private int syncWaitMsec;
109
110 public WALProcedureStore(final Configuration conf, final FileSystem fs, final Path logDir,
111 final LeaseRecovery leaseRecovery) {
112 this.fs = fs;
113 this.conf = conf;
114 this.logDir = logDir;
115 this.leaseRecovery = leaseRecovery;
116 }
117
118 @Override
119 public void start(int numSlots) throws IOException {
120 if (running.getAndSet(true)) {
121 return;
122 }
123
124
125 slots = new ByteSlot[numSlots];
126 slotsCache = new LinkedTransferQueue();
127 while (slotsCache.size() < numSlots) {
128 slotsCache.offer(new ByteSlot());
129 }
130
131
132 rollThreshold = conf.getLong(ROLL_THRESHOLD_CONF_KEY, DEFAULT_ROLL_THRESHOLD);
133 syncWaitMsec = conf.getInt(SYNC_WAIT_MSEC_CONF_KEY, DEFAULT_SYNC_WAIT_MSEC);
134 useHsync = conf.getBoolean(USE_HSYNC_CONF_KEY, DEFAULT_USE_HSYNC);
135
136
137 syncThread = new Thread("WALProcedureStoreSyncThread") {
138 @Override
139 public void run() {
140 while (running.get()) {
141 try {
142 syncLoop();
143 } catch (IOException e) {
144 LOG.error("got an exception from the sync-loop", e);
145 sendAbortProcessSignal();
146 }
147 }
148 }
149 };
150 syncThread.start();
151 }
152
153 @Override
154 public void stop(boolean abort) {
155 if (!running.getAndSet(false)) {
156 return;
157 }
158
159 LOG.info("Stopping the WAL Procedure Store");
160 if (lock.tryLock()) {
161 try {
162 waitCond.signalAll();
163 } finally {
164 lock.unlock();
165 }
166 }
167
168 if (!abort) {
169 try {
170 syncThread.join();
171 } catch (InterruptedException e) {
172 Thread.currentThread().interrupt();
173 }
174 }
175
176
177 closeStream();
178
179
180
181
182 for (ProcedureWALFile log: logs) {
183 log.close();
184 }
185 logs.clear();
186 }
187
188 @Override
189 public boolean isRunning() {
190 return running.get();
191 }
192
193 @Override
194 public int getNumThreads() {
195 return slots == null ? 0 : slots.length;
196 }
197
198 public ProcedureStoreTracker getStoreTracker() {
199 return storeTracker;
200 }
201
202 @Override
203 public void registerListener(ProcedureStoreListener listener) {
204 this.listeners.add(listener);
205 }
206
207 @Override
208 public boolean unregisterListener(ProcedureStoreListener listener) {
209 return this.listeners.remove(listener);
210 }
211
212 @Override
213 public void recoverLease() throws IOException {
214 LOG.info("Starting WAL Procedure Store lease recovery");
215 FileStatus[] oldLogs = getLogFiles();
216 while (running.get()) {
217
218 flushLogId = initOldLogs(oldLogs) + 1;
219
220
221 if (!rollWriter(flushLogId)) {
222
223 LOG.debug("someone else has already created log " + flushLogId);
224 continue;
225 }
226
227
228 oldLogs = getLogFiles();
229 if (getMaxLogId(oldLogs) > flushLogId) {
230
231 LOG.debug("someone else created new logs. expected maxLogId < " + flushLogId);
232 logs.getLast().removeFile();
233 continue;
234 }
235
236 LOG.info("lease acquired flushLogId=" + flushLogId);
237 break;
238 }
239 }
240
241 @Override
242 public Iterator<Procedure> load() throws IOException {
243 if (logs.isEmpty()) {
244 throw new RuntimeException("recoverLease() must be called before loading data");
245 }
246
247
248 if (logs.size() == 1) {
249 LOG.debug("No state logs to replay");
250 return null;
251 }
252
253
254 final ArrayList<ProcedureWALFile> toRemove = new ArrayList<ProcedureWALFile>();
255 Iterator<ProcedureWALFile> it = logs.descendingIterator();
256 it.next();
257 try {
258 return ProcedureWALFormat.load(it, storeTracker, new ProcedureWALFormat.Loader() {
259 @Override
260 public void removeLog(ProcedureWALFile log) {
261 toRemove.add(log);
262 }
263
264 @Override
265 public void markCorruptedWAL(ProcedureWALFile log, IOException e) {
266 if (corruptedLogs == null) {
267 corruptedLogs = new HashSet<ProcedureWALFile>();
268 }
269 corruptedLogs.add(log);
270
271 }
272 });
273 } finally {
274 if (!toRemove.isEmpty()) {
275 for (ProcedureWALFile log: toRemove) {
276 removeLogFile(log);
277 }
278 }
279 }
280 }
281
282 @Override
283 public void insert(final Procedure proc, final Procedure[] subprocs) {
284 if (LOG.isTraceEnabled()) {
285 LOG.trace("insert " + proc + " subproc=" + Arrays.toString(subprocs));
286 }
287
288 ByteSlot slot = acquireSlot();
289 long logId = -1;
290 try {
291
292 if (subprocs != null) {
293 ProcedureWALFormat.writeInsert(slot, proc, subprocs);
294 } else {
295 assert !proc.hasParent();
296 ProcedureWALFormat.writeInsert(slot, proc);
297 }
298
299
300 logId = pushData(slot);
301 } catch (IOException e) {
302
303
304 LOG.fatal("Unable to serialize one of the procedure: proc=" + proc +
305 " subprocs=" + Arrays.toString(subprocs), e);
306 throw new RuntimeException(e);
307 } finally {
308 releaseSlot(slot);
309 }
310
311
312 synchronized (storeTracker) {
313 storeTracker.insert(proc, subprocs);
314 }
315 }
316
317 @Override
318 public void update(final Procedure proc) {
319 if (LOG.isTraceEnabled()) {
320 LOG.trace("update " + proc);
321 }
322
323 ByteSlot slot = acquireSlot();
324 long logId = -1;
325 try {
326
327 ProcedureWALFormat.writeUpdate(slot, proc);
328
329
330 logId = pushData(slot);
331 } catch (IOException e) {
332
333
334 LOG.fatal("Unable to serialize the procedure: " + proc, e);
335 throw new RuntimeException(e);
336 } finally {
337 releaseSlot(slot);
338 }
339
340
341 boolean removeOldLogs = false;
342 synchronized (storeTracker) {
343 storeTracker.update(proc);
344 if (logId == flushLogId) {
345 removeOldLogs = storeTracker.isUpdated();
346 }
347 }
348
349 if (removeOldLogs) {
350 removeAllLogs(logId - 1);
351 }
352 }
353
354 @Override
355 public void delete(final long procId) {
356 if (LOG.isTraceEnabled()) {
357 LOG.trace("delete " + procId);
358 }
359
360 ByteSlot slot = acquireSlot();
361 long logId = -1;
362 try {
363
364 ProcedureWALFormat.writeDelete(slot, procId);
365
366
367 logId = pushData(slot);
368 } catch (IOException e) {
369
370
371 LOG.fatal("Unable to serialize the procedure: " + procId, e);
372 throw new RuntimeException(e);
373 } finally {
374 releaseSlot(slot);
375 }
376
377 boolean removeOldLogs = false;
378 synchronized (storeTracker) {
379 storeTracker.delete(procId);
380 if (logId == flushLogId) {
381 if (storeTracker.isEmpty() && totalSynced.get() > rollThreshold) {
382 removeOldLogs = rollWriterOrDie(logId + 1);
383 }
384 }
385 }
386
387 if (removeOldLogs) {
388 removeAllLogs(logId);
389 }
390 }
391
392 private ByteSlot acquireSlot() {
393 ByteSlot slot = slotsCache.poll();
394 return slot != null ? slot : new ByteSlot();
395 }
396
397 private void releaseSlot(final ByteSlot slot) {
398 slot.reset();
399 slotsCache.offer(slot);
400 }
401
402 private long pushData(final ByteSlot slot) {
403 assert isRunning() && !logs.isEmpty() : "recoverLease() must be called before inserting data";
404 long logId = -1;
405
406 lock.lock();
407 try {
408
409 while (true) {
410 if (inSync.get()) {
411 syncCond.await();
412 } else if (slotIndex == slots.length) {
413 slotCond.signal();
414 syncCond.await();
415 } else {
416 break;
417 }
418 }
419
420 slots[slotIndex++] = slot;
421 logId = flushLogId;
422
423
424 if (slotIndex == 1) {
425 waitCond.signal();
426 }
427
428
429 if (slotIndex == slots.length) {
430 waitCond.signal();
431 slotCond.signal();
432 }
433
434 syncCond.await();
435 } catch (InterruptedException e) {
436 Thread.currentThread().interrupt();
437 sendAbortProcessSignal();
438 } finally {
439 lock.unlock();
440 }
441 return logId;
442 }
443
444 private void syncLoop() throws IOException {
445 inSync.set(false);
446 while (running.get()) {
447 lock.lock();
448 try {
449
450 if (slotIndex == 0) {
451 if (LOG.isTraceEnabled()) {
452 float rollTsSec = (System.currentTimeMillis() - lastRollTs) / 1000.0f;
453 LOG.trace(String.format("Waiting for data. flushed=%s (%s/sec)",
454 StringUtils.humanSize(totalSynced.get()),
455 StringUtils.humanSize(totalSynced.get() / rollTsSec)));
456 }
457 waitCond.await();
458 if (slotIndex == 0) {
459
460 continue;
461 }
462 }
463
464
465 long syncWaitSt = System.currentTimeMillis();
466 if (slotIndex != slots.length) {
467 slotCond.await(syncWaitMsec, TimeUnit.MILLISECONDS);
468 }
469 long syncWaitMs = System.currentTimeMillis() - syncWaitSt;
470 if (LOG.isTraceEnabled() && (syncWaitMs > 10 || slotIndex < slots.length)) {
471 float rollSec = (System.currentTimeMillis() - lastRollTs) / 1000.0f;
472 LOG.trace("sync wait " + StringUtils.humanTimeDiff(syncWaitMs) +
473 " slotIndex=" + slotIndex +
474 " totalSynced=" + StringUtils.humanSize(totalSynced.get()) +
475 " " + StringUtils.humanSize(totalSynced.get() / rollSec) + "/sec");
476 }
477
478
479 inSync.set(true);
480 totalSynced.addAndGet(syncSlots());
481 slotIndex = 0;
482 inSync.set(false);
483 syncCond.signalAll();
484 } catch (InterruptedException e) {
485 Thread.currentThread().interrupt();
486 sendAbortProcessSignal();
487 } finally {
488 lock.unlock();
489 }
490 }
491 }
492
493 private long syncSlots() {
494 int retry = 0;
495 long totalSynced = 0;
496 do {
497 try {
498 totalSynced = syncSlots(stream, slots, 0, slotIndex);
499 break;
500 } catch (Throwable e) {
501 if (++retry == MAX_RETRIES_BEFORE_ABORT) {
502 LOG.error("sync slot failed, abort.", e);
503 sendAbortProcessSignal();
504 }
505 }
506 } while (running.get());
507 return totalSynced;
508 }
509
510 protected long syncSlots(FSDataOutputStream stream, ByteSlot[] slots, int offset, int count)
511 throws IOException {
512 long totalSynced = 0;
513 for (int i = 0; i < count; ++i) {
514 ByteSlot data = slots[offset + i];
515 data.writeTo(stream);
516 totalSynced += data.size();
517 }
518
519 if (useHsync) {
520 stream.hsync();
521 } else {
522 stream.hflush();
523 }
524
525 if (LOG.isTraceEnabled()) {
526 LOG.trace("Sync slots=" + count + '/' + slots.length +
527 " flushed=" + StringUtils.humanSize(totalSynced));
528 }
529 return totalSynced;
530 }
531
532 private void sendAbortProcessSignal() {
533 if (!this.listeners.isEmpty()) {
534 for (ProcedureStoreListener listener : this.listeners) {
535 listener.abortProcess();
536 }
537 }
538 }
539
540 private boolean rollWriterOrDie(final long logId) {
541 try {
542 return rollWriter(logId);
543 } catch (IOException e) {
544 LOG.warn("Unable to roll the log", e);
545 sendAbortProcessSignal();
546 return false;
547 }
548 }
549
550 private boolean rollWriter(final long logId) throws IOException {
551 ProcedureWALHeader header = ProcedureWALHeader.newBuilder()
552 .setVersion(ProcedureWALFormat.HEADER_VERSION)
553 .setType(ProcedureWALFormat.LOG_TYPE_STREAM)
554 .setMinProcId(storeTracker.getMinProcId())
555 .setLogId(logId)
556 .build();
557
558 FSDataOutputStream newStream = null;
559 Path newLogFile = null;
560 long startPos = -1;
561 try {
562 newLogFile = getLogFilePath(logId);
563 newStream = fs.create(newLogFile, false);
564 ProcedureWALFormat.writeHeader(newStream, header);
565 startPos = newStream.getPos();
566 } catch (FileAlreadyExistsException e) {
567 LOG.error("Log file with id=" + logId + " already exists", e);
568 return false;
569 }
570 lock.lock();
571 try {
572 closeStream();
573 synchronized (storeTracker) {
574 storeTracker.resetUpdates();
575 }
576 stream = newStream;
577 flushLogId = logId;
578 totalSynced.set(0);
579 lastRollTs = System.currentTimeMillis();
580 logs.add(new ProcedureWALFile(fs, newLogFile, header, startPos));
581 } finally {
582 lock.unlock();
583 }
584 LOG.info("Roll new state log: " + logId);
585 return true;
586 }
587
588 private void closeStream() {
589 try {
590 if (stream != null) {
591 try {
592 ProcedureWALFormat.writeTrailer(stream, storeTracker);
593 } catch (IOException e) {
594 LOG.warn("Unable to write the trailer: " + e.getMessage());
595 }
596 stream.close();
597 }
598 } catch (IOException e) {
599 LOG.error("Unable to close the stream", e);
600 } finally {
601 stream = null;
602 }
603 }
604
605 private void removeAllLogs(long lastLogId) {
606 LOG.info("Remove all state logs with ID less then " + lastLogId);
607 while (!logs.isEmpty()) {
608 ProcedureWALFile log = logs.getFirst();
609 if (lastLogId < log.getLogId()) {
610 break;
611 }
612
613 removeLogFile(log);
614 }
615 }
616
617 private boolean removeLogFile(final ProcedureWALFile log) {
618 try {
619 LOG.debug("remove log: " + log);
620 log.removeFile();
621 logs.remove(log);
622 } catch (IOException e) {
623 LOG.error("unable to remove log " + log, e);
624 return false;
625 }
626 return true;
627 }
628
629 public Set<ProcedureWALFile> getCorruptedLogs() {
630 return corruptedLogs;
631 }
632
633
634
635
636 public Path getLogDir() {
637 return this.logDir;
638 }
639
640 public FileSystem getFileSystem() {
641 return this.fs;
642 }
643
644 protected Path getLogFilePath(final long logId) throws IOException {
645 return new Path(logDir, String.format("state-%020d.log", logId));
646 }
647
648 private static long getLogIdFromName(final String name) {
649 int end = name.lastIndexOf(".log");
650 int start = name.lastIndexOf('-') + 1;
651 while (start < end) {
652 if (name.charAt(start) != '0')
653 break;
654 start++;
655 }
656 return Long.parseLong(name.substring(start, end));
657 }
658
659 private FileStatus[] getLogFiles() throws IOException {
660 try {
661 return fs.listStatus(logDir, new PathFilter() {
662 @Override
663 public boolean accept(Path path) {
664 String name = path.getName();
665 return name.startsWith("state-") && name.endsWith(".log");
666 }
667 });
668 } catch (FileNotFoundException e) {
669 LOG.warn("log directory not found: " + e.getMessage());
670 return null;
671 }
672 }
673
674 private long getMaxLogId(final FileStatus[] logFiles) {
675 long maxLogId = 0;
676 if (logFiles != null && logFiles.length > 0) {
677 for (int i = 0; i < logFiles.length; ++i) {
678 maxLogId = Math.max(maxLogId, getLogIdFromName(logFiles[i].getPath().getName()));
679 }
680 }
681 return maxLogId;
682 }
683
684
685
686
687 private long initOldLogs(final FileStatus[] logFiles) throws IOException {
688 this.logs.clear();
689
690 long maxLogId = 0;
691 if (logFiles != null && logFiles.length > 0) {
692 for (int i = 0; i < logFiles.length; ++i) {
693 final Path logPath = logFiles[i].getPath();
694 leaseRecovery.recoverFileLease(fs, logPath);
695 maxLogId = Math.max(maxLogId, getLogIdFromName(logPath.getName()));
696
697 ProcedureWALFile log = initOldLog(logFiles[i]);
698 if (log != null) {
699 this.logs.add(log);
700 }
701 }
702 Collections.sort(this.logs);
703 initTrackerFromOldLogs();
704 }
705 return maxLogId;
706 }
707
708 private void initTrackerFromOldLogs() {
709
710 if (!logs.isEmpty()) {
711 ProcedureWALFile log = logs.getLast();
712 try {
713 log.readTracker(storeTracker);
714 } catch (IOException e) {
715 LOG.warn("Unable to read tracker for " + log + " - " + e.getMessage());
716
717 storeTracker.clear();
718 storeTracker.setPartialFlag(true);
719 }
720 }
721 }
722
723 private ProcedureWALFile initOldLog(final FileStatus logFile) throws IOException {
724 ProcedureWALFile log = new ProcedureWALFile(fs, logFile);
725 if (logFile.getLen() == 0) {
726 LOG.warn("Remove uninitialized log " + logFile);
727 log.removeFile();
728 return null;
729 }
730
731 LOG.debug("opening state-log: " + logFile);
732 try {
733 log.open();
734 } catch (ProcedureWALFormat.InvalidWALDataException e) {
735 LOG.warn("Remove uninitialized log " + logFile, e);
736 log.removeFile();
737 return null;
738 } catch (IOException e) {
739 String msg = "Unable to read state log: " + logFile;
740 LOG.error(msg, e);
741 throw new IOException(msg, e);
742 }
743
744 if (log.isCompacted()) {
745 try {
746 log.readTrailer();
747 } catch (IOException e) {
748
749 LOG.warn("Unfinished compacted log " + logFile, e);
750 log.removeFile();
751 return null;
752 }
753 }
754 return log;
755 }
756 }