1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase;
19
20 import java.io.IOException;
21 import java.util.ArrayList;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.hadoop.util.Shell.ExitCodeException;
26 import org.apache.hadoop.util.Shell.ShellCommandExecutor;
27
28
29
30
31
32
33
34 class HealthChecker {
35
36 private static final Log LOG = LogFactory.getLog(HealthChecker.class);
37 private ShellCommandExecutor shexec = null;
38 private String exceptionStackTrace;
39
40
41 static private final String ERROR_PATTERN = "ERROR";
42
43 private String healthCheckScript;
44 private long scriptTimeout;
45
46 enum HealthCheckerExitStatus {
47 SUCCESS,
48 TIMED_OUT,
49 FAILED_WITH_EXIT_CODE,
50 FAILED_WITH_EXCEPTION,
51 FAILED
52 }
53
54
55
56
57
58
59 public void init(String location, long timeout) {
60 this.healthCheckScript = location;
61 this.scriptTimeout = timeout;
62 ArrayList<String> execScript = new ArrayList<String>();
63 execScript.add(healthCheckScript);
64 this.shexec = new ShellCommandExecutor(execScript.toArray(new String[execScript.size()]), null,
65 null, scriptTimeout);
66 LOG.info("HealthChecker initialized with script at " + this.healthCheckScript +
67 ", timeout=" + timeout);
68 }
69
70 public HealthReport checkHealth() {
71 HealthCheckerExitStatus status = HealthCheckerExitStatus.SUCCESS;
72 try {
73
74 shexec.execute();
75 } catch (ExitCodeException e) {
76
77 LOG.warn("Caught exception : " + e + ",exit code:" + e.getExitCode());
78 status = HealthCheckerExitStatus.FAILED_WITH_EXIT_CODE;
79 } catch (IOException e) {
80 LOG.warn("Caught exception : " + e);
81 status = HealthCheckerExitStatus.FAILED_WITH_EXCEPTION;
82 exceptionStackTrace = org.apache.hadoop.util.StringUtils.stringifyException(e);
83 } finally {
84 if (shexec.isTimedOut()) {
85 status = HealthCheckerExitStatus.TIMED_OUT;
86 }
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 }