JobClient.java
10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package com.github.ltsopensource.jobclient;
import com.github.ltsopensource.core.AppContext;
import com.github.ltsopensource.core.cluster.AbstractClientNode;
import com.github.ltsopensource.core.commons.utils.Assert;
import com.github.ltsopensource.core.commons.utils.BatchUtils;
import com.github.ltsopensource.core.commons.utils.CollectionUtils;
import com.github.ltsopensource.core.commons.utils.StringUtils;
import com.github.ltsopensource.core.constant.Constants;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.core.exception.JobSubmitException;
import com.github.ltsopensource.core.exception.JobTrackerNotFoundException;
import com.github.ltsopensource.core.logger.Logger;
import com.github.ltsopensource.core.logger.LoggerFactory;
import com.github.ltsopensource.core.protocol.JobProtos;
import com.github.ltsopensource.core.protocol.command.CommandBodyWrapper;
import com.github.ltsopensource.core.protocol.command.JobCancelRequest;
import com.github.ltsopensource.core.protocol.command.JobSubmitRequest;
import com.github.ltsopensource.core.protocol.command.JobSubmitResponse;
import com.github.ltsopensource.jobclient.domain.JobClientAppContext;
import com.github.ltsopensource.jobclient.domain.JobClientNode;
import com.github.ltsopensource.jobclient.domain.Response;
import com.github.ltsopensource.jobclient.domain.ResponseCode;
import com.github.ltsopensource.jobclient.processor.RemotingDispatcher;
import com.github.ltsopensource.jobclient.support.*;
import com.github.ltsopensource.remoting.AsyncCallback;
import com.github.ltsopensource.remoting.RemotingProcessor;
import com.github.ltsopensource.remoting.ResponseFuture;
import com.github.ltsopensource.remoting.protocol.RemotingCommand;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author Robert HG (254963746@qq.com) on 7/25/14.
* 任务客户端
*/
public class JobClient<T extends JobClientNode, Context extends AppContext> extends
AbstractClientNode<JobClientNode, JobClientAppContext> {
protected static final Logger LOGGER = LoggerFactory.getLogger(JobClient.class);
private static final int BATCH_SIZE = 10;
// 过载保护的提交者
private JobSubmitProtector protector;
protected JobClientMStatReporter stat;
public JobClient() {
this.stat = new JobClientMStatReporter(appContext);
// 监控中心
appContext.setMStatReporter(stat);
}
@Override
protected void beforeStart() {
appContext.setRemotingClient(remotingClient);
protector = new JobSubmitProtector(appContext);
}
@Override
protected void afterStart() {
appContext.getMStatReporter().start();
}
@Override
protected void afterStop() {
appContext.getMStatReporter().stop();
}
@Override
protected void beforeStop() {
}
public Response submitJob(Job job) throws JobSubmitException {
checkStart();
return protectSubmit(Collections.singletonList(job));
}
private Response protectSubmit(List<Job> jobs) throws JobSubmitException {
return protector.execute(jobs, new JobSubmitExecutor<Response>() {
@Override
public Response execute(List<Job> jobs) throws JobSubmitException {
return submitJob(jobs, SubmitType.ASYNC);
}
});
}
/**
* 取消任务
*/
public Response cancelJob(String taskId, String taskTrackerNodeGroup) {
checkStart();
final Response response = new Response();
Assert.hasText(taskId, "taskId can not be empty");
Assert.hasText(taskTrackerNodeGroup, "taskTrackerNodeGroup can not be empty");
JobCancelRequest request = CommandBodyWrapper.wrapper(appContext, new JobCancelRequest());
request.setTaskId(taskId);
request.setTaskTrackerNodeGroup(taskTrackerNodeGroup);
RemotingCommand requestCommand = RemotingCommand.createRequestCommand(
JobProtos.RequestCode.CANCEL_JOB.code(), request);
try {
RemotingCommand remotingResponse = remotingClient.invokeSync(requestCommand);
if (JobProtos.ResponseCode.JOB_CANCEL_SUCCESS.code() == remotingResponse.getCode()) {
LOGGER.info("Cancel job success taskId={}, taskTrackerNodeGroup={} ", taskId, taskTrackerNodeGroup);
response.setSuccess(true);
return response;
}
response.setSuccess(false);
response.setCode(JobProtos.ResponseCode.valueOf(remotingResponse.getCode()).name());
response.setMsg(remotingResponse.getRemark());
LOGGER.warn("Cancel job failed: taskId={}, taskTrackerNodeGroup={}, msg={}", taskId,
taskTrackerNodeGroup, remotingResponse.getRemark());
return response;
} catch (JobTrackerNotFoundException e) {
response.setSuccess(false);
response.setCode(ResponseCode.JOB_TRACKER_NOT_FOUND);
response.setMsg("Can not found JobTracker node!");
return response;
}
}
private void checkFields(List<Job> jobs) {
// 参数验证
if (CollectionUtils.isEmpty(jobs)) {
throw new JobSubmitException("Job can not be null!");
}
for (Job job : jobs) {
if (job == null) {
throw new JobSubmitException("Job can not be null!");
} else {
job.checkField();
}
}
}
protected Response submitJob(final List<Job> jobs, SubmitType type) throws JobSubmitException {
// 检查参数
checkFields(jobs);
final Response response = new Response();
try {
JobSubmitRequest jobSubmitRequest = CommandBodyWrapper.wrapper(appContext, new JobSubmitRequest());
jobSubmitRequest.setJobs(jobs);
RemotingCommand requestCommand = RemotingCommand.createRequestCommand(
JobProtos.RequestCode.SUBMIT_JOB.code(), jobSubmitRequest);
SubmitCallback submitCallback = new SubmitCallback() {
@Override
public void call(RemotingCommand responseCommand) {
if (responseCommand == null) {
response.setFailedJobs(jobs);
response.setSuccess(false);
response.setMsg("Submit Job failed: JobTracker is broken");
LOGGER.warn("Submit Job failed: {}, {}", jobs, "JobTracker is broken");
return;
}
if (JobProtos.ResponseCode.JOB_RECEIVE_SUCCESS.code() == responseCommand.getCode()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Submit Job success: {}", jobs);
}
response.setSuccess(true);
return;
}
// 失败的job
JobSubmitResponse jobSubmitResponse = responseCommand.getBody();
response.setFailedJobs(jobSubmitResponse.getFailedJobs());
response.setSuccess(false);
response.setCode(JobProtos.ResponseCode.valueOf(responseCommand.getCode()).name());
response.setMsg("Submit Job failed: " + responseCommand.getRemark() + " " + jobSubmitResponse.getMsg());
LOGGER.warn("Submit Job failed: {}, {}, {}", jobs, responseCommand.getRemark(), jobSubmitResponse.getMsg());
}
};
if (SubmitType.ASYNC.equals(type)) {
asyncSubmit(requestCommand, submitCallback);
} else {
syncSubmit(requestCommand, submitCallback);
}
} catch (JobTrackerNotFoundException e) {
response.setSuccess(false);
response.setCode(ResponseCode.JOB_TRACKER_NOT_FOUND);
response.setMsg("Can not found JobTracker node!");
} catch (Exception e) {
response.setSuccess(false);
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setMsg(StringUtils.toString(e));
} finally {
// 统计
if (response.isSuccess()) {
stat.incSubmitSuccessNum(jobs.size());
} else {
stat.incSubmitFailedNum(CollectionUtils.sizeOf(response.getFailedJobs()));
}
}
return response;
}
/**
* 异步提交任务
*/
private void asyncSubmit(RemotingCommand requestCommand, final SubmitCallback submitCallback)
throws JobTrackerNotFoundException {
final CountDownLatch latch = new CountDownLatch(1);
remotingClient.invokeAsync(requestCommand, new AsyncCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
try {
submitCallback.call(responseFuture.getResponseCommand());
} finally {
latch.countDown();
}
}
});
try {
latch.await(Constants.LATCH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new JobSubmitException("Submit job failed, async request timeout!", e);
}
}
/**
* 同步提交任务
*/
private void syncSubmit(RemotingCommand requestCommand, final SubmitCallback submitCallback)
throws JobTrackerNotFoundException {
submitCallback.call(remotingClient.invokeSync(requestCommand));
}
public Response submitJob(List<Job> jobs) throws JobSubmitException {
checkStart();
final Response response = new Response();
response.setSuccess(true);
int size = jobs.size();
BatchUtils.batchExecute(size, BATCH_SIZE, jobs, new BatchUtils.Executor<Job>() {
@Override
public boolean execute(List<Job> list) {
Response subResponse = protectSubmit(list);
if (!subResponse.isSuccess()) {
response.setSuccess(false);
response.addFailedJobs(list);
response.setMsg(subResponse.getMsg());
}
return true;
}
});
return response;
}
@Override
protected RemotingProcessor getDefaultProcessor() {
return new RemotingDispatcher(appContext);
}
/**
* 设置任务完成接收器
*/
public void setJobCompletedHandler(JobCompletedHandler jobCompletedHandler) {
appContext.setJobCompletedHandler(jobCompletedHandler);
}
enum SubmitType {
SYNC, // 同步
ASYNC // 异步
}
private void checkStart() {
if (!started.get()) {
throw new JobSubmitException("JobClient did not started");
}
}
}