/
AsyncProcessService.java
253 lines (232 loc) · 9.88 KB
/
AsyncProcessService.java
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
/*
* Copyright 2017, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.rest.service;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.jetbrains.annotations.NotNull;
import org.zanata.async.AsyncTaskHandle;
import org.zanata.async.AsyncTaskHandleManager;
import org.zanata.async.UserTriggerableTaskHandle;
import org.zanata.exception.AuthorizationException;
import org.zanata.rest.dto.ProcessStatus;
import org.zanata.rest.editor.service.SuggestionsService;
import org.zanata.security.ZanataIdentity;
import org.zanata.security.annotations.CheckRole;
import org.zanata.webtrans.shared.rest.dto.TransMemoryMergeCancelRequest;
import org.zanata.webtrans.shared.rest.dto.TransMemoryMergeRequest;
import com.google.common.annotations.VisibleForTesting;
import com.webcohesion.enunciate.metadata.rs.TypeHint;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* This endpoint should let us control and query all async tasks.
*
* TODO AsynchronousProcessResourceService are specific for CLI push and pull
* TODO org.zanata.rest.editor.service.SuggestionsService has specific methods for TM merge
*
* @see AsynchronousProcessResourceService
* @see SuggestionsService#merge(TransMemoryMergeRequest)
* @see SuggestionsService#cancelMerge(TransMemoryMergeCancelRequest)
*
* @author Patrick Huang
* <a href="mailto:pahuang@redhat.com">pahuang@redhat.com</a>
*/
@Path("/process")
@Produces(MediaType.APPLICATION_JSON)
public class AsyncProcessService implements RestResource {
private static final long serialVersionUID = 1L;
@Inject
private AsyncTaskHandleManager asyncTaskHandleManager;
@Inject
private ZanataIdentity identity;
@SuppressFBWarnings("SE_BAD_FIELD")
@Context
private UriInfo uriInfo;
public AsyncProcessService() {
}
// UriInfo can not be injected via constructor injection
@VisibleForTesting
AsyncProcessService(AsyncTaskHandleManager taskHandleManager,
ZanataIdentity identity, UriInfo uriInfo) {
asyncTaskHandleManager = taskHandleManager;
this.identity = identity;
this.uriInfo = uriInfo;
}
/**
* Get an async task's status.
*
* @param keyId
* task id
* @return The following response status codes will be returned from this
* operation:<br>
* OK(200) - The contents of the response will indicate the process
* identifier which may be used to query for its status or a message
* indicating what happened.<br>
* INTERNAL SERVER ERROR(500) - If there is an unexpected error in
* the server while performing this operation.
*/
@Path("key/{keyId}")
@GET
@TypeHint(ProcessStatus.class)
public Response getAsyncProcessStatus(@PathParam("keyId") String keyId) {
AsyncTaskHandle handle = asyncTaskHandleManager.getHandleByKeyId(keyId);
if (handle == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
ProcessStatus status = handleToProcessStatus(handle,
uriInfo.getRequestUri().toString());
return Response.ok(status).build();
}
/**
* Get statuses for all async tasks. This is for admin only.
*
* @param includeFinished
* whether to include finished tasks
*
* @return The following response status codes will be returned from this
* operation:<br>
* OK(200) - The contents of the response will indicate all
* background processes which may be used to query for its status or
* a message indicating what happened.<br>
* INTERNAL SERVER ERROR(500) - If there is an unexpected error in
* the server while performing this operation.
*/
@GET
@CheckRole("admin")
public Response getAllAsyncProcessStatuses(
@QueryParam("includeFinished") @DefaultValue("false") boolean includeFinished) {
Map<AsyncTaskHandleManager.AsyncTaskKey, AsyncTaskHandle> tasks;
if (includeFinished) {
tasks = asyncTaskHandleManager.getAllTasks();
} else {
tasks = asyncTaskHandleManager.getRunningTasks();
}
List<ProcessStatus> processStatuses = tasks.entrySet().stream()
.map(taskEntry -> handleToProcessStatus(taskEntry.getValue(),
uriInfo.getBaseUri() + "process/key/"
+ taskEntry.getKey().id()))
.collect(Collectors.toList());
return Response.ok(processStatuses).build();
}
/**
* Cancel a specific async task.
*
* @param keyId
* task id
*
* @return The following response status codes will be returned from this
* operation:<br>
* OK(200) - The contents of the response will indicate the process
* identifier which may be used to query for its status or a message
* indicating what happened.<br>
* INTERNAL SERVER ERROR(500) - If there is an unexpected error in
* the server while performing this operation.
*/
@POST
@Path("cancel/key/{keyId}")
public Response cancelAsyncProcess(@PathParam("keyId") String keyId) {
AsyncTaskHandle handle = asyncTaskHandleManager.getHandleByKeyId(keyId);
if (handle == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (!taskIsRunning(handle)) {
ProcessStatus entity = handleToProcessStatus(handle,
uriInfo.getBaseUri() + "process/key/" + keyId);
return Response.ok(entity).build();
}
if (handle instanceof UserTriggerableTaskHandle) {
UserTriggerableTaskHandle taskHandle =
(UserTriggerableTaskHandle) handle;
if (!taskHandle.canCancel(identity)) {
throw new AuthorizationException(
"Only the task owner or admin can cancel the task:" + keyId);
}
} else {
// for other type of async task, we consider them as system tasks
if (!identity.hasRole("admin")) {
throw new AuthorizationException(
"Only admin can cancel the task:" + keyId);
}
}
handle.cancel(true);
handle.setCancelledBy(identity.getAccountUsername());
handle.setCancelledTime(System.currentTimeMillis());
ProcessStatus processStatus = handleToProcessStatus(handle,
uriInfo.getBaseUri() + "process/cancel/key/" + keyId);
return Response.ok(processStatus).build();
}
private static boolean taskIsRunning(AsyncTaskHandle handle) {
return handle.isStarted() && !handle.isCancelled() && !handle.isDone();
}
@NotNull
static ProcessStatus handleToProcessStatus(AsyncTaskHandle handle,
String url) {
ProcessStatus status = new ProcessStatus();
status.setStatusCode(
handle.isDone() ? ProcessStatus.ProcessStatusCode.Finished
: ProcessStatus.ProcessStatusCode.Running);
int percentComplete = 100;
if (handle.getMaxProgress() > 0) {
percentComplete = (int) (handle.getCurrentProgress() * 100
/ handle.getMaxProgress());
}
status.setPercentageComplete(percentComplete);
status.setUrl(url);
if (handle.isCancelled()) {
status.setStatusCode(ProcessStatus.ProcessStatusCode.Cancelled);
status.addMessage("Cancelled by " + handle.getCancelledBy());
} else if (handle.isDone()) {
Object result = null;
try {
result = handle.getResult();
} catch (InterruptedException e) {
// The process was forcefully cancelled
status.setStatusCode(ProcessStatus.ProcessStatusCode.Failed);
status.addMessage(e.getMessage());
} catch (ExecutionException e) {
// Exception thrown while running the task
status.setStatusCode(ProcessStatus.ProcessStatusCode.Failed);
status.addMessage(e.getCause().getMessage());
} catch (Exception e) {
status.setStatusCode(ProcessStatus.ProcessStatusCode.Failed);
status.addMessage("Unknown exception:" + e.getMessage());
}
// TODO Need to find a generic way of returning all object types.
if (result != null) {
status.addMessage(result.toString());
}
}
return status;
}
}