1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.coordination;
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.atomic.AtomicInteger;
27 import java.util.concurrent.atomic.AtomicLong;
28
29 import org.apache.commons.lang.math.RandomUtils;
30 import org.apache.commons.lang.mutable.MutableInt;
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.hadoop.conf.Configuration;
34 import org.apache.hadoop.fs.FileSystem;
35 import org.apache.hadoop.fs.Path;
36 import org.apache.hadoop.hbase.HConstants;
37 import org.apache.hadoop.hbase.ServerName;
38 import org.apache.hadoop.hbase.SplitLogCounters;
39 import org.apache.hadoop.hbase.SplitLogTask;
40 import org.apache.hadoop.hbase.classification.InterfaceAudience;
41 import org.apache.hadoop.hbase.exceptions.DeserializationException;
42 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
43 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
44 import org.apache.hadoop.hbase.regionserver.Region;
45 import org.apache.hadoop.hbase.regionserver.RegionServerServices;
46 import org.apache.hadoop.hbase.regionserver.SplitLogWorker;
47 import org.apache.hadoop.hbase.regionserver.SplitLogWorker.TaskExecutor;
48 import org.apache.hadoop.hbase.regionserver.handler.FinishRegionRecoveringHandler;
49 import org.apache.hadoop.hbase.regionserver.handler.WALSplitterHandler;
50 import org.apache.hadoop.hbase.util.CancelableProgressable;
51 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
52 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
53 import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
54 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
55 import org.apache.hadoop.hbase.zookeeper.ZooKeeperListener;
56 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
57 import org.apache.hadoop.util.StringUtils;
58 import org.apache.zookeeper.AsyncCallback;
59 import org.apache.zookeeper.KeeperException;
60 import org.apache.zookeeper.data.Stat;
61
62
63
64
65
66
67 @InterfaceAudience.Private
68 public class ZkSplitLogWorkerCoordination extends ZooKeeperListener implements
69 SplitLogWorkerCoordination {
70
71 private static final Log LOG = LogFactory.getLog(ZkSplitLogWorkerCoordination.class);
72
73 private static final int checkInterval = 5000;
74 private static final int FAILED_TO_OWN_TASK = -1;
75
76 private SplitLogWorker worker;
77
78 private TaskExecutor splitTaskExecutor;
79
80 private final Object taskReadyLock = new Object();
81 private AtomicInteger taskReadySeq = new AtomicInteger(0);
82 private volatile String currentTask = null;
83 private int currentVersion;
84 private volatile boolean shouldStop = false;
85 private final Object grabTaskLock = new Object();
86 private boolean workerInGrabTask = false;
87 private int reportPeriod;
88 private RegionServerServices server = null;
89 protected final AtomicInteger tasksInProgress = new AtomicInteger(0);
90 private int maxConcurrentTasks = 0;
91
92 private final ZkCoordinatedStateManager manager;
93
94 public ZkSplitLogWorkerCoordination(ZkCoordinatedStateManager zkCoordinatedStateManager,
95 ZooKeeperWatcher watcher) {
96 super(watcher);
97 manager = zkCoordinatedStateManager;
98
99 }
100
101
102
103
104 @Override
105 public void nodeChildrenChanged(String path) {
106 if (path.equals(watcher.splitLogZNode)) {
107 if (LOG.isTraceEnabled()) LOG.trace("tasks arrived or departed on " + path);
108 synchronized (taskReadyLock) {
109 this.taskReadySeq.incrementAndGet();
110 taskReadyLock.notify();
111 }
112 }
113 }
114
115
116
117
118 @Override
119 public void nodeDataChanged(String path) {
120
121
122 synchronized (grabTaskLock) {
123 if (workerInGrabTask) {
124
125 String taskpath = currentTask;
126 if (taskpath != null && taskpath.equals(path)) {
127 getDataSetWatchAsync();
128 }
129 }
130 }
131 }
132
133
134
135
136 @Override
137 public void init(RegionServerServices server, Configuration conf,
138 TaskExecutor splitExecutor, SplitLogWorker worker) {
139 this.server = server;
140 this.worker = worker;
141 this.splitTaskExecutor = splitExecutor;
142 maxConcurrentTasks = conf.getInt("hbase.regionserver.wal.max.splitters", DEFAULT_MAX_SPLITTERS);
143 reportPeriod =
144 conf.getInt("hbase.splitlog.report.period",
145 conf.getInt(HConstants.HBASE_SPLITLOG_MANAGER_TIMEOUT,
146 ZKSplitLogManagerCoordination.DEFAULT_TIMEOUT) / 3);
147 }
148
149
150
151 void getDataSetWatchFailure(String path) {
152 synchronized (grabTaskLock) {
153 if (workerInGrabTask) {
154
155 String taskpath = currentTask;
156 if (taskpath != null && taskpath.equals(path)) {
157 LOG.info("retrying data watch on " + path);
158 SplitLogCounters.tot_wkr_get_data_retry.incrementAndGet();
159 getDataSetWatchAsync();
160 } else {
161
162
163 }
164 }
165 }
166 }
167
168 public void getDataSetWatchAsync() {
169 watcher.getRecoverableZooKeeper().getZooKeeper()
170 .getData(currentTask, watcher, new GetDataAsyncCallback(), null);
171 SplitLogCounters.tot_wkr_get_data_queued.incrementAndGet();
172 }
173
174 void getDataSetWatchSuccess(String path, byte[] data) {
175 SplitLogTask slt;
176 try {
177 slt = SplitLogTask.parseFrom(data);
178 } catch (DeserializationException e) {
179 LOG.warn("Failed parse", e);
180 return;
181 }
182 synchronized (grabTaskLock) {
183 if (workerInGrabTask) {
184
185 String taskpath = currentTask;
186 if (taskpath != null && taskpath.equals(path)) {
187 ServerName serverName = manager.getServer().getServerName();
188
189
190
191
192
193
194 if (!slt.isOwned(serverName) && !slt.isDone(serverName) && !slt.isErr(serverName)
195 && !slt.isResigned(serverName)) {
196 LOG.info("task " + taskpath + " preempted from " + serverName
197 + ", current task state and owner=" + slt.toString());
198 worker.stopTask();
199 }
200 }
201 }
202 }
203 }
204
205
206
207
208
209
210 private boolean grabTask(String path) {
211 Stat stat = new Stat();
212 byte[] data;
213 synchronized (grabTaskLock) {
214 currentTask = path;
215 workerInGrabTask = true;
216 if (Thread.interrupted()) {
217 return false;
218 }
219 }
220 try {
221 try {
222 if ((data = ZKUtil.getDataNoWatch(watcher, path, stat)) == null) {
223 SplitLogCounters.tot_wkr_failed_to_grab_task_no_data.incrementAndGet();
224 return false;
225 }
226 } catch (KeeperException e) {
227 LOG.warn("Failed to get data for znode " + path, e);
228 SplitLogCounters.tot_wkr_failed_to_grab_task_exception.incrementAndGet();
229 return false;
230 }
231 SplitLogTask slt;
232 try {
233 slt = SplitLogTask.parseFrom(data);
234 } catch (DeserializationException e) {
235 LOG.warn("Failed parse data for znode " + path, e);
236 SplitLogCounters.tot_wkr_failed_to_grab_task_exception.incrementAndGet();
237 return false;
238 }
239 if (!slt.isUnassigned()) {
240 SplitLogCounters.tot_wkr_failed_to_grab_task_owned.incrementAndGet();
241 return false;
242 }
243
244 currentVersion =
245 attemptToOwnTask(true, watcher, server.getServerName(), path,
246 slt.getMode(), stat.getVersion());
247 if (currentVersion < 0) {
248 SplitLogCounters.tot_wkr_failed_to_grab_task_lost_race.incrementAndGet();
249 return false;
250 }
251
252 if (ZKSplitLog.isRescanNode(watcher, currentTask)) {
253 ZkSplitLogWorkerCoordination.ZkSplitTaskDetails splitTaskDetails =
254 new ZkSplitLogWorkerCoordination.ZkSplitTaskDetails();
255 splitTaskDetails.setTaskNode(currentTask);
256 splitTaskDetails.setCurTaskZKVersion(new MutableInt(currentVersion));
257
258 endTask(new SplitLogTask.Done(server.getServerName(), slt.getMode()),
259 SplitLogCounters.tot_wkr_task_acquired_rescan, splitTaskDetails);
260 return false;
261 }
262
263 LOG.info("worker " + server.getServerName() + " acquired task " + path);
264 SplitLogCounters.tot_wkr_task_acquired.incrementAndGet();
265 getDataSetWatchAsync();
266
267 submitTask(path, slt.getMode(), currentVersion, reportPeriod);
268
269
270 try {
271 int sleepTime = RandomUtils.nextInt(500) + 500;
272 Thread.sleep(sleepTime);
273 } catch (InterruptedException e) {
274 LOG.warn("Interrupted while yielding for other region servers", e);
275 Thread.currentThread().interrupt();
276 }
277 return true;
278 } finally {
279 synchronized (grabTaskLock) {
280 workerInGrabTask = false;
281
282
283 Thread.interrupted();
284 }
285 }
286 }
287
288
289
290
291
292
293 void submitTask(final String curTask, final RecoveryMode mode, final int curTaskZKVersion,
294 final int reportPeriod) {
295 final MutableInt zkVersion = new MutableInt(curTaskZKVersion);
296
297 CancelableProgressable reporter = new CancelableProgressable() {
298 private long last_report_at = 0;
299
300 @Override
301 public boolean progress() {
302 long t = EnvironmentEdgeManager.currentTime();
303 if ((t - last_report_at) > reportPeriod) {
304 last_report_at = t;
305 int latestZKVersion =
306 attemptToOwnTask(false, watcher, server.getServerName(), curTask,
307 mode, zkVersion.intValue());
308 if (latestZKVersion < 0) {
309 LOG.warn("Failed to heartbeat the task" + curTask);
310 return false;
311 }
312 zkVersion.setValue(latestZKVersion);
313 }
314 return true;
315 }
316 };
317 ZkSplitLogWorkerCoordination.ZkSplitTaskDetails splitTaskDetails =
318 new ZkSplitLogWorkerCoordination.ZkSplitTaskDetails();
319 splitTaskDetails.setTaskNode(curTask);
320 splitTaskDetails.setCurTaskZKVersion(zkVersion);
321
322 WALSplitterHandler hsh =
323 new WALSplitterHandler(server, this, splitTaskDetails, reporter,
324 this.tasksInProgress, splitTaskExecutor, mode);
325 server.getExecutorService().submit(hsh);
326 }
327
328 private boolean areSplittersAvailable() {
329 return maxConcurrentTasks - tasksInProgress.get() > 0;
330 }
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345 protected static int attemptToOwnTask(boolean isFirstTime, ZooKeeperWatcher zkw,
346 ServerName server, String task, RecoveryMode mode, int taskZKVersion) {
347 int latestZKVersion = FAILED_TO_OWN_TASK;
348 try {
349 SplitLogTask slt = new SplitLogTask.Owned(server, mode);
350 Stat stat = zkw.getRecoverableZooKeeper().setData(task, slt.toByteArray(), taskZKVersion);
351 if (stat == null) {
352 LOG.warn("zk.setData() returned null for path " + task);
353 SplitLogCounters.tot_wkr_task_heartbeat_failed.incrementAndGet();
354 return FAILED_TO_OWN_TASK;
355 }
356 latestZKVersion = stat.getVersion();
357 SplitLogCounters.tot_wkr_task_heartbeat.incrementAndGet();
358 return latestZKVersion;
359 } catch (KeeperException e) {
360 if (!isFirstTime) {
361 if (e.code().equals(KeeperException.Code.NONODE)) {
362 LOG.warn("NONODE failed to assert ownership for " + task, e);
363 } else if (e.code().equals(KeeperException.Code.BADVERSION)) {
364 LOG.warn("BADVERSION failed to assert ownership for " + task, e);
365 } else {
366 LOG.warn("failed to assert ownership for " + task, e);
367 }
368 }
369 } catch (InterruptedException e1) {
370 LOG.warn("Interrupted while trying to assert ownership of " + task + " "
371 + StringUtils.stringifyException(e1));
372 Thread.currentThread().interrupt();
373 }
374 SplitLogCounters.tot_wkr_task_heartbeat_failed.incrementAndGet();
375 return FAILED_TO_OWN_TASK;
376 }
377
378
379
380
381
382
383
384
385
386
387 @Override
388 public void taskLoop() throws InterruptedException {
389 while (!shouldStop) {
390 int seq_start = taskReadySeq.get();
391 List<String> paths = null;
392 paths = getTaskList();
393 if (paths == null) {
394 LOG.warn("Could not get tasks, did someone remove " + watcher.splitLogZNode
395 + " ... worker thread exiting.");
396 return;
397 }
398
399 int offset = (int) (Math.random() * paths.size());
400 for (int i = 0; i < paths.size(); i++) {
401 if (DefaultWALProvider.isMetaFile(paths.get(i))) {
402 offset = i;
403 break;
404 }
405 }
406 int numTasks = paths.size();
407 boolean taskGrabbed = false;
408 for (int i = 0; i < numTasks; i++) {
409 while (!shouldStop) {
410 if (this.areSplittersAvailable()) {
411 if (LOG.isTraceEnabled()) {
412 LOG.trace("Current region server " + server.getServerName()
413 + " is ready to take more tasks, will get task list and try grab tasks again.");
414 }
415 int idx = (i + offset) % paths.size();
416
417
418 taskGrabbed |= grabTask(ZKUtil.joinZNode(watcher.splitLogZNode, paths.get(idx)));
419 break;
420 } else {
421 if (LOG.isTraceEnabled()) {
422 LOG.trace("Current region server " + server.getServerName() + " has "
423 + this.tasksInProgress.get() + " tasks in progress and can't take more.");
424 }
425 Thread.sleep(100);
426 }
427 }
428 if (shouldStop) {
429 return;
430 }
431 }
432 if (!taskGrabbed && !shouldStop) {
433
434 Thread.sleep(1000);
435 }
436 SplitLogCounters.tot_wkr_task_grabing.incrementAndGet();
437 synchronized (taskReadyLock) {
438 while (seq_start == taskReadySeq.get()) {
439 taskReadyLock.wait(checkInterval);
440 if (server != null) {
441
442 Map<String, Region> recoveringRegions = server.getRecoveringRegions();
443 if (!recoveringRegions.isEmpty()) {
444
445
446 List<String> tmpCopy = new ArrayList<String>(recoveringRegions.keySet());
447 int listSize = tmpCopy.size();
448 for (int i = 0; i < listSize; i++) {
449 String region = tmpCopy.get(i);
450 String nodePath = ZKUtil.joinZNode(watcher.recoveringRegionsZNode, region);
451 try {
452 if (ZKUtil.checkExists(watcher, nodePath) == -1) {
453 server.getExecutorService().submit(
454 new FinishRegionRecoveringHandler(server, region, nodePath));
455 } else {
456
457
458
459
460
461 break;
462 }
463 } catch (KeeperException e) {
464
465 LOG.debug("Got a zookeeper when trying to open a recovering region", e);
466 break;
467 }
468 }
469 }
470 }
471 }
472 }
473 }
474 }
475
476 private List<String> getTaskList() throws InterruptedException {
477 List<String> childrenPaths = null;
478 long sleepTime = 1000;
479
480
481 while (!shouldStop) {
482 try {
483 childrenPaths =
484 ZKUtil.listChildrenAndWatchForNewChildren(watcher,
485 watcher.splitLogZNode);
486 if (childrenPaths != null) {
487 return childrenPaths;
488 }
489 } catch (KeeperException e) {
490 LOG.warn("Could not get children of znode " + watcher.splitLogZNode, e);
491 }
492 LOG.debug("Retry listChildren of znode " + watcher.splitLogZNode
493 + " after sleep for " + sleepTime + "ms!");
494 Thread.sleep(sleepTime);
495 }
496 return childrenPaths;
497 }
498
499 @Override
500 public void markCorrupted(Path rootDir, String name, FileSystem fs) {
501 ZKSplitLog.markCorrupted(rootDir, name, fs);
502 }
503
504 @Override
505 public boolean isReady() throws InterruptedException {
506 int result = -1;
507 try {
508 result = ZKUtil.checkExists(watcher, watcher.splitLogZNode);
509 } catch (KeeperException e) {
510
511 LOG.warn("Exception when checking for " + watcher.splitLogZNode
512 + " ... retrying", e);
513 }
514 if (result == -1) {
515 LOG.info(watcher.splitLogZNode
516 + " znode does not exist, waiting for master to create");
517 Thread.sleep(1000);
518 }
519 return (result != -1);
520 }
521
522 @Override
523 public int getTaskReadySeq() {
524 return taskReadySeq.get();
525 }
526
527 @Override
528 public void registerListener() {
529 watcher.registerListener(this);
530 }
531
532 @Override
533 public void removeListener() {
534 watcher.unregisterListener(this);
535 }
536
537
538 @Override
539 public void stopProcessingTasks() {
540 this.shouldStop = true;
541
542 }
543
544 @Override
545 public boolean isStop() {
546 return shouldStop;
547 }
548
549 @Override
550 public RegionStoreSequenceIds getRegionFlushedSequenceId(String failedServerName, String key)
551 throws IOException {
552 return ZKSplitLog.getRegionFlushedSequenceId(watcher, failedServerName, key);
553 }
554
555
556
557
558 class GetDataAsyncCallback implements AsyncCallback.DataCallback {
559 private final Log LOG = LogFactory.getLog(GetDataAsyncCallback.class);
560
561 @Override
562 public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
563 SplitLogCounters.tot_wkr_get_data_result.incrementAndGet();
564 if (rc != 0) {
565 LOG.warn("getdata rc = " + KeeperException.Code.get(rc) + " " + path);
566 getDataSetWatchFailure(path);
567 return;
568 }
569 data = watcher.getRecoverableZooKeeper().removeMetaData(data);
570 getDataSetWatchSuccess(path, data);
571 }
572 }
573
574
575
576
577
578
579
580
581
582
583 @Override
584 public void endTask(SplitLogTask slt, AtomicLong ctr, SplitTaskDetails details) {
585 ZkSplitTaskDetails zkDetails = (ZkSplitTaskDetails) details;
586 String task = zkDetails.getTaskNode();
587 int taskZKVersion = zkDetails.getCurTaskZKVersion().intValue();
588 try {
589 if (ZKUtil.setData(watcher, task, slt.toByteArray(), taskZKVersion)) {
590 LOG.info("successfully transitioned task " + task + " to final state " + slt);
591 ctr.incrementAndGet();
592 return;
593 }
594 LOG.warn("failed to transistion task " + task + " to end state " + slt
595 + " because of version mismatch ");
596 } catch (KeeperException.BadVersionException bve) {
597 LOG.warn("transisition task " + task + " to " + slt + " failed because of version mismatch",
598 bve);
599 } catch (KeeperException.NoNodeException e) {
600 LOG.fatal(
601 "logic error - end task " + task + " " + slt + " failed because task doesn't exist", e);
602 } catch (KeeperException e) {
603 LOG.warn("failed to end task, " + task + " " + slt, e);
604 }
605 SplitLogCounters.tot_wkr_final_transition_failed.incrementAndGet();
606 }
607
608
609
610
611
612 public static class ZkSplitTaskDetails implements SplitTaskDetails {
613 private String taskNode;
614 private MutableInt curTaskZKVersion;
615
616 public ZkSplitTaskDetails() {
617 }
618
619 public ZkSplitTaskDetails(String taskNode, MutableInt curTaskZKVersion) {
620 this.taskNode = taskNode;
621 this.curTaskZKVersion = curTaskZKVersion;
622 }
623
624 public String getTaskNode() {
625 return taskNode;
626 }
627
628 public void setTaskNode(String taskNode) {
629 this.taskNode = taskNode;
630 }
631
632 public MutableInt getCurTaskZKVersion() {
633 return curTaskZKVersion;
634 }
635
636 public void setCurTaskZKVersion(MutableInt curTaskZKVersion) {
637 this.curTaskZKVersion = curTaskZKVersion;
638 }
639
640 @Override
641 public String getWALFile() {
642 return ZKSplitLog.getFileName(taskNode);
643 }
644 }
645
646 }