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;
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.apache.hadoop.util.Shell.ExitCodeException;
28 import org.apache.hadoop.util.Shell.ShellCommandExecutor;
29
30
31
32
33
34
35 class HealthChecker {
36
37 private static Log LOG = LogFactory.getLog(HealthChecker.class);
38 private ShellCommandExecutor shexec = null;
39 private String exceptionStackTrace;
40
41
42 static private final String ERROR_PATTERN = "ERROR";
43
44 private String healthCheckScript;
45 private long scriptTimeout;
46
47 enum HealthCheckerExitStatus {
48 SUCCESS,
49 TIMED_OUT,
50 FAILED_WITH_EXIT_CODE,
51 FAILED_WITH_EXCEPTION,
52 FAILED
53 }
54
55
56
57
58
59
60 public void init(String location, long timeout) {
61 this.healthCheckScript = location;
62 this.scriptTimeout = timeout;
63 ArrayList<String> execScript = new ArrayList<String>();
64 execScript.add(healthCheckScript);
65 this.shexec = new ShellCommandExecutor(execScript.toArray(new String[execScript.size()]), null,
66 null, scriptTimeout);
67 LOG.info("HealthChecker initialized.");
68 }
69
70 public HealthReport checkHealth() {
71 HealthCheckerExitStatus status = HealthCheckerExitStatus.SUCCESS;
72 try {
73 shexec.execute();
74 } catch (ExitCodeException e) {
75
76 LOG.warn("Caught exception : " + e);
77 status = HealthCheckerExitStatus.FAILED_WITH_EXIT_CODE;
78 } catch (IOException e) {
79 LOG.warn("Caught exception : " + e);
80 if (!shexec.isTimedOut()) {
81 status = HealthCheckerExitStatus.FAILED_WITH_EXCEPTION;
82 exceptionStackTrace = org.apache.hadoop.util.StringUtils.stringifyException(e);
83 } else {
84 status = HealthCheckerExitStatus.TIMED_OUT;
85 }
86 } finally {
87 if (status == HealthCheckerExitStatus.SUCCESS) {
88 if (hasErrors(shexec.getOutput())) {
89 status = HealthCheckerExitStatus.FAILED;
90 }
91 }
92 }
93 return new HealthReport(status, getHealthReport(status));
94 }
95
96 private boolean hasErrors(String output) {
97 String[] splits = output.split("\n");
98 for (String split : splits) {
99 if (split.startsWith(ERROR_PATTERN)) {
100 return true;
101 }
102 }
103 return false;
104 }
105
106 private String getHealthReport(HealthCheckerExitStatus status){
107 String healthReport = null;
108 switch (status) {
109 case SUCCESS:
110 healthReport = "Server is healthy.";
111 break;
112 case TIMED_OUT:
113 healthReport = "Health script timed out";
114 break;
115 case FAILED_WITH_EXCEPTION:
116 healthReport = exceptionStackTrace;
117 break;
118 case FAILED_WITH_EXIT_CODE:
119 healthReport = "Health script failed with exit code.";
120 break;
121 case FAILED:
122 healthReport = shexec.getOutput();
123 break;
124 }
125 return healthReport;
126 }
127 }